【问题标题】:Deduce template parameter of class推导出类的模板参数
【发布时间】:2017-10-04 12:58:43
【问题描述】:

谁能帮我理解为什么下面的代码不能编译:

#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 的模板参数 Tint

【问题讨论】:

    标签: c++ templates c++14 type-deduction template-templates


    【解决方案1】:
    • 你还没有声明T。它需要是一个模板参数。

    • T 放入template &lt;class T&gt; class GENERAL_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)
    {}
    

    【讨论】:

      【解决方案2】:

      bolov's answer 在所有方面都是正确的。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-09
        • 2015-09-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多