【问题标题】:C++ compiler error on template specialization模板专业化上的 C++ 编译器错误
【发布时间】:2011-03-05 11:53:38
【问题描述】:

我想为本身的类 C 专门化一个模板方法 由 int 参数模板化。

我该怎么做?

template <int D=1>
class C {
    static std::string  foo () { stringstream ss; ss << D << endl; return ss.str();}    
};

template <class X>
void test() { cout << "This is a test" << endl;}

template <>
template <int D>
void test<C<D> > () {cout << C<D>::foo() << endl;}

test() 的特化失败,出现“void test() 声明中的模板参数列表太多”。

【问题讨论】:

    标签: c++ compiler-errors template-specialization


    【解决方案1】:

    不允许函数模板部分特化。做

    template <int D>  
    void test () {cout << C<D>::foo() << endl;}
    

    【讨论】:

      【解决方案2】:

      您不希望在 test&lt;C&lt;D&gt;&gt; 的部分特化中出现第一个 template&lt;&gt;。此外,您只能部分特化类模板,而不是函数模板。这样的事情可能会奏效:

      template <class X>
      struct thing
      {
          static void test() { cout << "This is a test" << endl;}
      };
      
      template <int D>
      struct thing<C<D>>
      {
          static void test() {cout << C<D>::foo() << endl;}
      };
      

      如果您的函数模板接受一个参数,并使用它来推断模板参数,那么您可以使用重载获得类似的效果,例如:

      template <class X>
      void test(const X&) { cout << "This is a test" << endl;}
      
      template <int D>
      void test(const C<D>&) {cout << C<D>::foo() << endl;}
      
      test(3);  // calls first version
      test(C<3>()); // calls second version
      

      【讨论】:

      • 那行不通。现在我收到一条消息:不允许部分专业化'test>'
      • 哦,是的,我忘记了。您只能部分特化类模板。
      • 如果C == std::tuple 怎么办?还有D == Args... 可变参数模板?))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 2020-07-18
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      相关资源
      最近更新 更多