【问题标题】:Specializing a function of a template class特化模板类的功能
【发布时间】:2015-05-31 19:41:04
【问题描述】:

这在 C++ 中是合法的:

template <int N> class A {
    void bar() {std::cout << N << '\n';}
};

template<>
void A<2>::bar() {std::cout << "Two\n";}  // This is ok.

现在考虑这个类:

template <int...> struct B;

template <int First, int... Rest>
struct B<First, Rest...> : B<Rest...> {
    static void foo() {
        std::cout << First << ' ';
        B<Rest...>::foo();  
    }
    static void bar() {/*Bunch of code*/}
    static void baz() {/*Bunch of code*/}
};

template <>
struct B<> {
    static void foo() {}
    static void bar() {}
    static void baz() {}
};

那为什么下面这个是非法的(放在上面):

template <int... Rest>
void B<2, Rest...>::foo() {  // Illegal.
    std::cout << "Two ";
    B<Rest...>::foo();
}

我不明白为什么B&lt;2, Rest...&gt; 是不完整的类型,如错误消息所述。显然,实现我想要的唯一方法就是通过这个?

template <int... Rest>
struct B<2, Rest...> : B<Rest...> {
    static void foo() {
        std::cout << "Two ";
        B<Rest...>::foo();  
    }
    static void bar() {/*Same bunch of code as above*/}
    static void baz() {/*Same bunch of code as above*/}
};

因此重复bar()和baz()中的所有代码?

【问题讨论】:

  • 第一个是显式特化(可以);第二个是部分专业化(不是)。

标签: c++ templates specialization


【解决方案1】:

您试图实现的称为部分模板特化,并且只允许用于类,而不允许用于函数。例如见Why function template cannot be partially specialized?

【讨论】:

  • 我知道这条规则,但我认为这里的部分特化更多地与类有关,而不是与函数有关。毕竟,错误消息指向 B&lt;2, Rest...&gt; 是一个不完整的类型。所以没有令人满意的解决方法,是吗?
  • 该链接与此问题无关 - OP 并未尝试部分专门化功能模板。
  • 但是人们投票支持我。我还认为在发布我的问题之前我并没有尝试对函数模板进行部分专业化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-14
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多