c++ - 专门化模板类中的模板结构

标签 c++ c++11

template <class T1, class T2>
class A {

template <typename T>
struct BarSelector {
    void bar(T*) {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

template <> struct BarSelector<D> {
    void bar(D*) {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

public:
    void foo(T2* pT2) {
        // do something
        BarSelector<T2> selector;
        selector.bar(pT2);
    }
};

int main() {
    C c;
    A<B, C> a1;
    a1.foo(&c);

    D* pD;
    A<B, D> a2;
    a2.foo(pD);
}

编译器给出:

toverloading.cpp:20:11: error: explicit specialization in non-namespace scope ‘class A<T1, T2>’
 template <> struct BarSelector<D> {
           ^
toverloading.cpp:20:20: error: template parameters not used in partial specialization:
 template <> struct BarSelector<D> {
                    ^
toverloading.cpp:20:20: error:         ‘T1’
toverloading.cpp:20:20: error:         ‘T2’

如果我将 BarSelector 移到 A 类之外,它就会起作用。

将它们保留在 A 类中的正确语法是什么?

谢谢!

最佳答案

What's the correct syntax to keep them inside class A?

不,显式特化不能放在类范围内,它必须放在命名空间范围内。

来自标准,$14.7.3/2 显式特化 [temp.expl.spec]

An explicit specialization shall be declared in a namespace enclosing the specialized template.

所以你得把它移到类外面,比如:

template<> 
template<> 
class A<B, D>::BarSelector<D> {
    void bar(double*) {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }
};

请注意,如果不显式特化包含类,就不可能特化成员。这可能是关于为什么不能在类范围内显式特化成员模板的旁注(这使您可以在不显式特化外部类模板的情况下特化成员模板)。

关于c++ - 专门化模板类中的模板结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35318293/

相关文章:

c++ - 排序算法是否应该在比较函数中传递相同的元素

c++ - 将 lambda 表达式传递给模板函数时出现编译错误

c++ - 双向迭代容器

c++ - 编写一个函数来获取字符串输入

c++ - 所有共线点的凸包?

c++ - 替换 glaux 函数

C++:友好模板参数的模板类型成员的正确语法?

c++ - 作为可变参数模板的结构化参数

c++ - 为什么 C++11 允许 GC?

c++ - 以最高性能将 double vector 截断为单精度