头文件中有如下代码:
template<typename A, typename B> class TemplateTest;
template<>
class TemplateTest<int, double>
{
public:
float operator() (float a);
};
cpp文件中的定义:
template<> // this is problematic line
float TemplateTest<int, double>::operator()(float a)
{
float b;
b = a + 5;
return b;
}
对于定义中的“template<>”,MSVC 返回错误 C2910,因为它将 operator() 解释为模板方法而不是模板类的方法。 GCC 的行为类似。但是 Solaris CC 需要“template<>”(否则它会发出错误“显式特化 ... 的成员时需要“template<>”语法”。
所以我的问题是哪一个是正确的以及如何使代码在所有这些平台上编译。
最佳答案
Solaris CC 不正确。 template<>
不允许。 C++14 标准 [temp.expl.spec]/5:
Members of an explicitly specialized class template are defined in the same manner as members of normal classes, and not using the
template<>
syntax. ...[ Example:
template<class T> struct A {
struct B { };
template<class U> struct C { };
};
template<> struct A<int> {
void f(int);
};
void h() {
A<int> a;
a.f(16); // A<int>::f must be defined somewhere
}
// template<> not used for a member of an
// explicitly specialized class template
void A<int>::f(int) { /*...*/ }
... - end example ]
看起来支持 Solaris CC,你将不得不使用类似的东西:
#ifdef __SUNPRO_CC
template <>
#endif
float TemplateTest<int, double>::operator()(float a)
{
float b;
b = a + 5;
return b;
}
如果您有很多这样的文件,您可能希望将该样板文件放入自定义宏中。
关于c++ - Solaris CC 要求的 template<> 语法,但被 MSVC 和 GCC 禁止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46780197/