来自这段代码:
// Example program
#include <iostream>
#include <string>
struct Z { static const int z = 1; };
struct Y { static const int y = 2; };
template <typename A> struct TE { int foo(); int bar(); };
template <> int TE<Y>::bar() { return foo(); }
template <typename A> int TE<A>::bar() { return foo(); }
template <> int TE<Y>::foo() { return Y::y; }
template <typename A> int TE<A>::foo() { return A::z; }
template struct TE<Z>;
template struct TE<Y>;
int main()
{
TE<Z> z;
TE<Y> y;
std::cout << z.bar() << std::endl;
std::cout << y.bar() << std::endl;
return 0;
}
有这个错误
21:28: error: specialization of 'int TE<A>::foo() [with A = Y]' after instantiation
In instantiation of 'int TE<A>::foo() [with A = Y]':
13:12: required from here
28:15: error: 'z' is not a member of 'Y'
In member function 'int TE<A>::foo() [with A = Y]':
29:1: warning: control reaches end of non-void function [-Wreturn-type]
这些实现是在单独的 cpp 文件中完成的。并且结构在 header 中,典型的显式模板实例化。
为什么会这样
int TE<Y>::bar() { return foo(); }
尝试使用它
template <typename A> int TE<A>::foo() { return A::z; }
而不是这个
template <> int TE<Y>::foo() { return Y::y; }
最佳答案
http://en.cppreference.com/w/cpp/language/template_specialization
显式特化只能出现在与主模板相同的命名空间中,并且必须出现在非特化模板声明之后。
此外,您还需要遵循单一定义规则 (ODR)。所以通常您会在同一个标头中提供您的实现。
关于c++ - 为什么这个显式模板特化不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36597490/