从这个线程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++编译命令。
我得到了以下两个错误-
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<>,第一个错误就会消失,这让我更加担心,因为我知道专门化并没有像我想要的那样发生。
2号错误不会消失。
我对模板类成员函数的专门化越来越困惑。我在这里错过了什么?g++抱怨的原因是什么?有什么想法吗?
谢谢!
发布于 2012-08-10 02:43:07
我不确定你所说的“专业化没有像我希望的那样发生”是什么意思。你到底想要什么?
在您的代码中,您正在尝试执行模板类成员的显式专门化,而不是专门化类本身。C++中所有形式的显式专门化都需要template<>语法
template<>
inline bool A_0::dummy(void *value)
{
// Whatever
}
template<>
inline bool A_1::dummy(void *value)
{
// Whatever
}在C++中就是这样。仅仅因为您将专用类名“隐藏”在类型定义名称后面并不意味着您就不必使用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;
}https://stackoverflow.com/questions/11889765
复制相似问题