Search code examples
c++templatesc++14type-deductiontemplate-templates

Deduce template parameter of class


Can someone please help me to understand why the following code does not compile:

#include <type_traits>

template< typename T >
class A
{};

template< typename T >
class B
{};

template< template <typename T> class GENERAL_t,  // Note: GENERAL_t is either A<T> or B<T>
          typename = std::enable_if_t< std::is_same<T,int>::value >
        >
void foo( GENERAL_t a )
{}

error message:

t.cpp:67:57: error: use of undeclared identifier 'T'
              typename = std::enable_if_t< std::is_same<T,int>::value >
                                                        ^
t.cpp:67:65: error: no type named 'value' in the global namespace
              typename = std::enable_if_t< std::is_same<T,int>::value >
                                                              ~~^
t.cpp:69:15: error: use of class template 'GENERAL_t' requires template arguments
    void foo( GENERAL_t a )
              ^
t.cpp:66:43: note: template is declared here
    template< template <typename T> class GENERAL_t,  // Note: GENERAL_t is either A<T> or B<T>
              ~~~~~~~~~~~~~~~~~~~~~       ^
3 errors generated.

Here, foo should take instances of class A or class B but only when the template argument T of A or B is an int.


Solution

    • you haven't declared T. It needs to be a template parameter.

    • drop the T in the template <class T> class GENERAL_t

    • GENERAL_t is a template template and as such requires a template parameter.

    • please don't use ALL_CAPS for anything except macros

    This is the working code:

    template<class T, template <class> class General_t, 
              class = std::enable_if_t< std::is_same<T,int>::value >
            >
    void foo(General_t<T> a)
    {}