我从这个线程知道 - 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<>
,1 就会消失之前 inline bool A_0::dummy(void *value)
这让我更加担心,因为我知道特化并没有按照我的意愿发生。
错误编号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<>
语法。
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;
}
关于c++ - 模板类成员函数的特化 - 在 Linux 上使用 g++-4.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11889765/