cpp 文件中模板成员的显式实例不会生成符号(即 link 错误)
Explicit instantiantion of template member in cpp file doesn't generate symbol (i.e. link error)
举个例子:
// A.h
class A
{
public:
int v = 2;
template <typename T>
int f(T t);
};
// A.cpp
#include "A.h"
template <typename T>
int A::f(T t)
{
return v + t;
}
template <>
int A::f<int>(int t);
// main.cpp
#include <stdio.h>
#include "A.h"
int main()
{
A a;
printf("%d\n", a.f(3));
return 0;
}
使用 clang -std=c++14
(或 g++)构建时,出现以下错误:
main.cpp:8: undefined reference to `int A::f<int>(int)'
的确,nm A.o
没有显示任何符号。 A.cpp
里面A::f<int>
的显式实例化为什么没有实际实例化函数?
我想@JaMiT 找到了答案。
template <> int A::f<int>(int t)
{
// full specialization of templated thing
}
是一个完整的专业。
template <> int A::f<int>(int t);
是这样的专业化存在的声明,但不提供定义。
你想要的形式是
template int A::f<int>(int t);
这是成员函数的实例化。
举个例子:
// A.h
class A
{
public:
int v = 2;
template <typename T>
int f(T t);
};
// A.cpp
#include "A.h"
template <typename T>
int A::f(T t)
{
return v + t;
}
template <>
int A::f<int>(int t);
// main.cpp
#include <stdio.h>
#include "A.h"
int main()
{
A a;
printf("%d\n", a.f(3));
return 0;
}
使用 clang -std=c++14
(或 g++)构建时,出现以下错误:
main.cpp:8: undefined reference to `int A::f<int>(int)'
的确,nm A.o
没有显示任何符号。 A.cpp
里面A::f<int>
的显式实例化为什么没有实际实例化函数?
我想@JaMiT 找到了答案。
template <> int A::f<int>(int t)
{
// full specialization of templated thing
}
是一个完整的专业。
template <> int A::f<int>(int t);
是这样的专业化存在的声明,但不提供定义。
你想要的形式是
template int A::f<int>(int t);
这是成员函数的实例化。