模板类的成员函数的专用化 - 在 Linux 上使用 g++-4.7

Specialization of Member Function of a Template Class - on Linux using g++-4.7

本文关键字:Linux g++-4 成员 函数 专用      更新时间:2023-10-16

我从这个线程中知道 - 模板类成员函数仅专业化如果我专门化类模板,我需要专化所有成员函数。

所以,我的理由是我会"实例化"一个模板类。 (不确定这是否是正确的表达方式)

然后,由于这个实例化类是一个成熟的类,我可以专门化一个特定的方法。

// I have a template class like this - 
template<class T, T invalidVal, int e> class A
{ 
     static inline bool dummy(T value) 
    {
        return 0;
    }
 }
 // Now I create classes from the above template class with 
 // T=void*, invalidVal=NULL & e=0 
 // And with T=void *, invalidVal=NULL & e=1 
 // And I typedef these classes to use them later
 typedef A<void *, (void *)NULL, 0> A_0;
 typedef A<void *, (void *)NULL, 1> A_1;
 // So now, what I was expecting was that A_0 & A_1 are classes and 
 // they can have their own specialized dummy() method
 // So I tried following - 
 inline bool A_0::dummy(void *value) 
 {
     return value != invalidVal;
 }
 inline bool A_1::dummy(void *value)
 {
     return value == invalidVal;
 }

上面的代码在Windows环境中工作。(Visual Studio 2008)

但是这种专业化在 Linux 上使用 g++-4.7 不起作用。通过阅读其他一些线程,我也将 -std=c++11 传递给我的 g++ 编译命令。

我收到以下 2 个错误 -

1. specializing member ‘A<void*, 0u, 0>::dummy’ requires ‘template<>’ syntax 
2. invalidVal was not declared in this scope

现在,如果我在inline bool A_0::dummy(void *value)之前添加一个template<>,错误 1 就会消失,这让我更加担心,因为我知道专业化并没有按照我的意愿发生。

错误 2 不会消失。

我对模板类成员函数专用化越来越困惑。我在这里错过了什么?g++抱怨的原因是什么?有什么想法吗?

谢谢!

我不确定你所说的"专业化没有按照我想要的方式发生"是什么意思。你到底想要什么?

在您的代码中,您尝试对模板类成员执行显式专用化,而不专用于类本身。C++中所有形式的显式专用化都需要template<>语法

template<>
inline bool A_0::dummy(void *value) 
{
  // Whatever
}
template<>
inline bool A_1::dummy(void *value)
{
  // Whatever
}

这就是C++的方式。仅仅因为你"隐藏"了 typedef-names 后面的专用类名并不意味着你不必使用 template<> 语法。

视觉C++显然允许您跳过template <>部分作为非标准扩展。

此外,专用版本对模板参数名称一无所知(它们不再有任何参数),这意味着它们完全不知道名称invalidVal。要么将invalidVal替换为显式NULL(如显式参数列表中),要么通过类使值作为常量静态成员invalidVal可用

template<class T, T invalidVal, int e> class A
{ 
  static const T iv; // declaration
  ...
};
template <class T, T invalidVal, int e>
const T A<T, invalidVal, e>::iv = invalidVal; // definition
template <> inline bool A_0::dummy(void *value) 
{
   return value != iv;
}