如果我在C++中使用内联函数,为什么要重新定义'template <class T>?

The*_*Guy 0 c++ templates inline

我有2个头文件相同的头文件:

template<typename T> inline void func(){

}
Run Code Online (Sandbox Code Playgroud)

我在main.cpp文件中包含这两个头文件然后编译:

g++ main.cpp -o run
Run Code Online (Sandbox Code Playgroud)

但我得到:

In file included from main.cpp:2:0:
test2.cpp:1:34: error: redefinition of ‘template<class T> void func()’
 template<typename T> inline void func(){
                                  ^
In file included from main.cpp:1:0:
test.cpp:1:34: error: ‘template<class T> void func()’ previously declared here
 template<typename T> inline void func(){
Run Code Online (Sandbox Code Playgroud)

如果使用可以重新定义的内联函数,我会得到什么错误?

Nat*_*ica 5

你错过了一个关键部分.该标准在[basic.def.odr]/6中说明了

类类型(第9条),枚举类型(7.2),带内部链接的内联函数(7.1.2),类模板(第14条),非静态函数模板(14.5.6)可以有多个定义,类模板的静态数据成员(14.5.1.3),类模板的成员函数(14.5.1.1),或者在程序中未指定某些模板参数(14.7,14.5.5)的模板特化,前提是每个模板定义出现在不同的翻译单元 [...]

强调我的

因此,您可以拥有内联函数的多个定义,但这些定义需要位于单独的转换单元(基本上是源文件)中.由于它们处于相同的翻译单元中,因此它们违反了该规则并且您收到错误.