Search code examples
c++templatesnon-type-template-parameter

templates <int T> C++


What does it mean to define a template with template <int N>, I read this from an example in a book:

typedef map<int, double> row;
template <int N> struct matrix;
{
   map <int, row> my_matrix;
}

I have usually seen templates which are followed by class and then type, i.e. template <class int>


Solution

  • Template parameters may be of any of the three kinds of C++ entities: values, types, or templates:

    template <int N> struct Foo;                        // N is a value
    
    template <typename T> struct Bar;                   // T is a type
    
    template <template <typename> class X> struct Zip;  // X is a template
    

    Example usage:

    Foo<10> a;
    
    Bar<int> b;
    
    Zip<Bar> c;
    

    Note that this corresponds to the three ways of disamiguating dependent names:

    X::a = 10;              // X::a is a value
    typename X::B n = 10;   // X::B is a type
    X::template C<int> m;   // X::C is a template
    

    An interesting combination arises when you want to "typify" a value. This can be done like so:

    template <typename T, T Val> struct Typificate;
    

    Now you can say e.g. Typificate<int, 10> to get a unique type that represents the integer 10. This can occasionally be very useful, e.g. when T is a member function pointer (e.g. in this delegate implementation); or it can be used to create value-unique overloads for tag dispatch, etc.