简体   繁体   English

专门化模板类的功能

[英]Specializing a function of a template class

This is legal in C++: 这在C ++中是合法的:

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

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

Now consider this class: 现在考虑这个类:

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

Then why is the following illegal (placed after the above): 那么为什么以下是非法的(放在上面):

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

I don't see why B<2, Rest...> is an incomplete type, as the error message states. 我不明白为什么B<2, Rest...>是一个不完整的类型,正如错误消息所述。 So apparently, the only way to achieve what I want is through this? 显然,实现我想要的唯一方法是通过这个?

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*/}
};

Thus repeating all the code in bar() and baz()? 因此重复bar()和baz()中的所有代码?

What you are trying to achieve is called partial template specialization, and is allowed only for classes, not for functions. 您要实现的目标称为部分模板特化,并且仅允许用于类,而不允许用于函数。 See for example Why function template cannot be partially specialized? 请参阅示例为什么函数模板不能部分专用?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM