单独声明和定义模板函数的专门化:成员函数和非成员函数的不同行为
Separate declaration and definition of specialization of template function : different behaviour for member and nonmember functions
我想为函数模板声明专门化,但稍后在源文件中定义它。考虑下一个例子:
.hpp
// approach #1
template <typename T> const char *GetTypeName();
template <> const char *GetTypeName<int>();
// approach #2
template <typename T> class TypeName {static const char *Get();};
template <> const char *TypeName<int>::Get();
.cpp
// approach #1
template <> const char *GetTypeName<int>()
{
return "int"
}
// approach #2
template <> const char *TypeName<int>::Get()
{
return "int"
}
在MSVC 2012 (CTP是不是安装),两个变体编译良好,但非成员变体(#1)引发链接器错误(未解决的外部,等等)。这是正常行为吗?MSVC具体?编译器错误?固定在CTP?
编辑
我只使用专门的版本。它们在头文件中声明,在源文件中定义。此方法适用于成员函数,但不适用于独立函数。
编辑2
嗯…我试图在家里构建相同的快照(相同的MSVC安装,没有CTP),它链接没有问题。似乎是本地错误或安装损坏。
函数模板不是函数。完全专门化的函数模板是函数。
由于必须定义所有(odr使用的)函数,因此必须有一种方法来生成任意模板实例化的定义。因此,主函数模板的定义必须在头文件中。
header.h:
template <typename T> // this
const char * GetTypeName() // is
{ // not
return "foo"; // a
} // function
template <>
const char * GetTypeName<int>();
impl.cpp:
#include "header.h"
template <>
const char * GetTypeName<int>()
{
return "int";
}
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针