c++templatestemplate-templatesdefault-template-argument

Template default argument


How do I specify a template class as a default value for a template typename? e.g. the following doesn't work.

template <typename A, typename B> class X {};

template <typename T=template <typename, typename> class X> class Y {};

int main()
{
    Y<> y;
    return 0;
} 
tmp.cc:4:22: error: expected type-specifier before ‘template’
 template <typename T=template <typename, typename> class X> class Y {};
                      ^~~~~~~~
tmp.cc:4:22: error: expected ‘>’ before ‘template’
tmp.cc: In function ‘int main()’:
tmp.cc:8:7: error: template argument 1 is invalid
     Y<> y;
       ^

Solution

  • The problem of your code is that for Y you ask a type template parameter and you want to use a template template parameter.

    template <typename A, typename B> class X {};
    
    //           type                template template
    //........VVVVVVVVVV VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
    template <typename T=template <typename, typename> class X> class Y {};
    
    int main()
    {
        Y<> y;
        return 0;
    } 
    

    If you want to use X as default, T must be be a template template, so

    template <typename, typename>
    class X
     {};
    
    template <template <typename, typename> class T = X>
    class Y
     {};
    
    int main ()
     {
       Y<> y;
     } 
    

    Or also using variadics to improve flexibility

    template <template <typename...> class T = X>
    class Y
     {};