单独声明和定义模板函数的专门化:成员函数和非成员函数的不同行为

Separate declaration and definition of specialization of template function : different behaviour for member and nonmember functions

本文关键字:函数 成员 声明 单独 专门化 定义      更新时间:2023-10-16

我想为函数模板声明专门化,但稍后在源文件中定义它。考虑下一个例子:

.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";
}