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

时间:2012-08-09 18:32:19

标签: c++ linux templates g++ partial-specialization

我从这个帖子中知道 - template class member function only specialization 如果我专门化一个类模板,我需要专门化所有成员函数。

所以,我的理由是我会“实例化”一个模板类。 (不确定它是否正确的说法)

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

// 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

现在,错误号码。如果我在template<>之前添加一个inline bool A_0::dummy(void *value),这会让我更加担心,因为我知道专业化并没有像我想的那样发生。

错误号。 2不会消失。

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

谢谢!

1 个答案:

答案 0 :(得分:3)

我不确定我的意思是“专业化没有按照我的意愿发生”。你究竟想要什么?

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

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

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

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

Visual 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;
}