模板类的成员函数的专用化 - 在 Linux 上使用 g++-4.7
Specialization of Member Function of a Template Class - on Linux using g++-4.7
我从这个线程中知道 - 模板类成员函数仅专业化如果我专门化类模板,我需要专化所有成员函数。
所以,我的理由是我会"实例化"一个模板类。 (不确定这是否是正确的表达方式)
然后,由于这个实例化类是一个成熟的类,我可以专门化一个特定的方法。
// 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;
}
- 在C++/Linux中设置单调时钟的一些技巧
- Linux的Cpp上的计时器
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 在Linux中哪里可以找到互斥、未来等的源代码
- 如何在linux终端中同时编译和运行c++代码
- 在Linux for Windows上编译C++代码时出错
- 如何找到锁定Linux futex的C++行
- 在linux上调试巨大的C++项目
- 如何处理linux终端中带有负号(-)的C++中的命令行参数
- c++方法参数只能在linux的发布模式下自行更改
- 在Linux和C++中的Windows上,散列字符串值会产生不同的输出
- 这里在 Linux 中具有"CreatePipe"和"CreateProcessW"功能吗?
- 函数在Windows或Linux上运行时表现不同
- 在Linux下捕获SIGKILL的C++程序
- 在为LINUX创建共享库时,如何避免STL的私有/弱副本
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- 如何在CPP中创建应该在Windows和Linux上运行的套接字?
- mysql C++ connector [mysql-connector-c++-8.0.19-linux-glibc2
- 这些是什么样的错误?即使我不在 Linux 上工作,我也遇到了 Linux 错误
- CMake WxWidgets项目成功地在Linux上构建,但没有在Windows上构建