假设我有一个在template.h
中声明并在template.cpp
中定义的非类型模板函数f(int)
(参数<int dim>
)。在template.cpp
我进一步为dim = 2
添加了一项专业化,然后我明确地实例化了dim = 1
和dim = 2
的模板函数。为什么我不能使用单个非类型参数内联显式实例化模板函数?
该文件编译罚款,但在连接过程中,我得到一个错误:
Undefined symbols for architecture x86_64:
"void f<2>(int)", referenced from:
_main in main-2AW7ED.o
ld: symbol(s) not found for architecture x86_64
但是,如果我删除模板专业化inline
关键字(见下文标记),整个事情按预期工作。因此,我的问题来了:
为什么inline
不适用于专用模板,当它适用于基本模板时,其他所有内容编译和工作正常?
main.cpp中
#include <iostream>
#include "template.h"
using namespace std;
int main(int, char**)
{
f<1>(456);
f<2>(789);
}
template.h
template <int dim> void f(int src);
template.cpp
#include <iostream>
#include "template.h"
using namespace std;
template <int dim> inline
void f(int src)
{
cout << "src = " << src << endl;
cout << "dim (template) = " << dim << endl;
}
template <> inline // <== if I remove this "inline", everything works as expected
void f<2>(int src)
{
cout << "src = " << src << endl;
cout << "dim (fixed) = " << 2 << endl;
}
template void f<1>(int);
template void f<2>(int);
P.S .:我用g ++和clang ++来编译命令clang++ -o tmpl template.cpp main.cpp
。
为什么你还没有在template.h中的声明上定义'inline'? –
这实质上是一个ODR违规行为。 –
@TonyD从http://www.parashift。com/C++ - faq-lite/where-to-put-inline-keyword.html和其他来源我知道我只需要把它放在一个位置。 –