gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:44:40 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com