简体   繁体   中英

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 .

  • 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)
{}

bolov's answer is correct in all respects.

But in this case, you don't need the SFINAE on is_same . You can just template on the template-template:

template <template <class> class General>
void foo(General<int> ) { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM