模板<> Solaris CC 需要的语法,但 MSVC 和 GCC 禁止

template<> syntax required by Solaris CC, but forbidden by MSVC and GCC

本文关键字:MSVC GCC 禁止 语法 gt lt Solaris CC 模板      更新时间:2023-10-16

>我在头文件中有以下代码:

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 标准 [临时规范]/5:

显式专用类模板的成员的定义方式与普通类的成员相同,并且不使用template<>语法。

[ 示例:

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) { /*...*/ }

... - 结束示例 ]

看起来要支持 Solaris CC,您必须使用类似的东西:

#ifdef __SUNPRO_CC
template <>
#endif
float TemplateTest<int, double>::operator()(float a)
{
    float b;
    b = a + 5;
    return b;
}

如果您有很多这样的样板,您可能希望将该样板放入自定义宏中。

你不需要

template<>   // this is problematic line

完整示例:

template<typename A, typename B>  class TemplateTest;
template<>
class TemplateTest<int, double>
{
public:
    float operator() (float a);
};
float TemplateTest<int, double>::operator()(float a)
{
    return 0;
}

魔杖盒

在C++参考中查找"专业成员"