Porting C ++ to C # - Templates

I port the C ++ application to C # and run the templates. I read a little about this, and I understand that some templates are akin to .Net generics. I read the SO answer in this case, which summed up well.

However, some uses of C ++ templates are not directly related to generics. In the Wikipedia example below, the metaprogramming pattern of the article seems to take on value, not type. I'm not quite sure how this will 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
}

Obviously, for this example, I could do:

public int Factorial(int N){
    if(N == 0) return 1;
    return Factorial(N - 1);
}

but it seems to me that this is refactoring for a function, not a port for semantically similar code.

+5
5

, .Net . ++ Templates , , , .

, - . call .Value( ), , :

return Factorial(N-1).Value;
+5

... , , , .

. # , . 1

, # . , 0 1, , . # .

, (generic) , , . # generics arent Turing , ++-.


1 - :

class Zero { }

class Successor<T> : Zero where T : Zero { }

// one:
Successor<Zero>
// two:
Successor<Successor<Zero>>
// etc.

.

+5

# generics ++ :

, .

MSDN

+3

, , ++, # generics. , non, .

+1

, :

public class Factorial<T>
    where T : IConvertible 
    {
        public T GetFactorial(T t)
        {
            int int32 = Convert.ToInt32(t);
            if (int32 == 0)
                return (T) Convert.ChangeType( 1, typeof(T));
            return GetFactorial( (T) Convert.ChangeType(int32-1, typeof(T)) );
        }
    }

, ValueTypes. , Int16 Int32. Int64.

0

All Articles