c++ - Solaris CC 要求的 template<> 语法,但被 MSVC 和 GCC 禁止

标签 c++ templates gcc cc

头文件中有如下代码:

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/

相关文章:

c++ - 如何使用 boost.program_options 处理多个语法命令行参数

c++ - 我如何从 std::list.begin() 中强制一个非常量迭代器?

c++ - 如何将类方法作为参数传递给另一个函数并稍后调用它,最好使变量类方法签名显式?

c++ - 防止两个类从具有相同模板参数的基类继承

c++ - 在类模板定义中使用模板名称代替模板标识

c++ - 因为 std::swap(s1, s2) 就足够了,所以 string::swap 可以忽略吗?

c++ - 关于函数指针数组声明的疑问

c - 警告 : data definition has no type or storage class despite including header

linux - 如何避免二进制文件中的 STT_GNU_IFUNC 符号?

ubuntu - 在 SSH 中生成文件后无法启动文件