内联函数模板特化

Nik*_*iou 1 c++

以下代码位于.h文件中(包含保护)

template<typename T1, typename T2> // a
void func(T1 const &t1, T2 const &t2)
{
    std::cout << "\nbase template"; 
}

template<> // b
inline void func<int, int>(int const &t1, int const &t2)
{
    std::cout << "\nspecialization for integers";
}
Run Code Online (Sandbox Code Playgroud)

从(b)中删除inline关键字时,以下代码(从包含.h的.cpp调用)将无法编译

func<int, int>(1, 2);
Run Code Online (Sandbox Code Playgroud)

发出链接器错误"错误LNK2005:"void __cdecl func(int const&,int const&)"(?? $ func @HH @@ YAXABH0 @ Z)已在ConsoleApplication1.obj中定义"

为什么会这样?

编辑:

因为它们是定义(由Luchian Grigore回答),显式特化是否意味着显式实例化或者这个编译器是否具体?

Luc*_*ore 5

因为显式特化是定义,因此在多个翻译单元中包含该文件会导致多次定义符号,这会破坏一个定义规则.

除了标记它之外inline,您可以将声明留在标题中并将定义移动到实现文件中.