假設我有一個在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和其他來源我知道我只需要把它放在一個位置。 –