c++templates

How to create type T and value of type T template with default type T?


As question says. I'd like to create a template, e.g. of class, that takes in typename T and T val as parameters, in which I can specify default T type.

I tried this:

template <typename T = int, T V = 0>
class Example
{

};

Example<int, 1> a; // compiles
Example<int> a; // compiles
Example a; // compiles
Example<1> a; // Error: "expected type specifier"

but the one thing I would like to work does not.

How can I do this right?


Solution

  • You are trying to pass an integer literal 1 where a typename is expected. That obviously will not work.

    Unfortunately, partial template specialization will not work, either:

    template <typename T = int, T V = T{}>
    class Example
    {
    };
    
    template <int N>
    class Example<int, N>
    {
    };
    
    /* alternatively:
    
    template<auto T>
    class Example<decltype(T), T>
    {
    
    };
    
    */
    
    Example<int, 1> a; // compiles
    Example<int> a; // compiles
    Example a; // compiles
    Example<1> a; // Error
    

    But, a type alias will work:

    template <typename T = int, T V = T{}>
    class Example
    {
    };
    
    template <int N>
    using Example_int = Example<int, N>;
    
    Example<int, 1> a; // compiles
    Example<int> a; // compiles
    Example a; // compiles
    Example_int<1> a; // compiles