专门化模板类的功能

时间:2015-05-31 19:41:04

标签: c++ templates specialization

这在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<2, Rest...>是一个不完整的类型,正如错误消息所述。显然,实现我想要的唯一方法是通过这个?

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()中的所有代码?

1 个答案:

答案 0 :(得分:0)

您要实现的目标称为部分模板特化,并且仅允许用于类,而不允许用于函数。请参阅示例Why function template cannot be partially specialized?

相关问题