推导 class 的模板参数

Deduce template parameter of class

谁能帮我理解为什么以下代码无法编译:

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

错误信息:

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.

此处,foo 应采用 class Aclass B 的实例,但仅当 AB 的模板参数 T 时是一个 int.

  • 您还没有申报 T。它需要是一个模板参数。

  • template <class T> class GENERAL_t

  • 中删除 T
  • GENERAL_t 是模板模板,因此需要模板参数。

  • 请不要将 ALL_CAPS 用于宏以外的任何内容

这是工作代码:

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

各方面都是正确的。

但在这种情况下,您不需要 is_same 上的 SFINAE。你可以只在模板模板上模板:

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