I'm porting a C++ application to C#, and have run across templates. I've read up a little on these, and I understand that some templates are akin to .Net generics. I read the SO answer to this case which nicely summed it up.
However, some uses of c++ templating don't seem to be directly related to generics. In the below example from Wikipedia's Template metaprogramming article the template seems to accept a value, rather than a type. I'm not quite sure how this would be ported to C#?
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
Clearly for this example I could do:
public int Factorial(int N){
if(N == 0) return 1;
return Factorial(N - 1);
}
but this seems to me to be a refactoring to a function, rather than a port to semantically similar code.