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

Why am I getting redefinition of ‘template<class T> if I use inline function in C++?

我有 2 个 header 个内容相同的文件:

template<typename T> inline void func(){

}

我将这 2 个 header 包含在 main.cpp 文件中,然后编译:

g++ main.cpp -o run

但我得到:

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(){

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

因为One Definition Rule (ODR).

In any translation unit, a template, type, function, or object can have no more than one definition. Some of these can have any number of declarations. A definition provides an instance.

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

There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit[...]

强调我的

因此,您可以对内联函数有多个定义,但这些定义需要在单独的翻译单元(基本上是源文件)中。由于他们在同一个翻译单元中,他们违反了这一点,你会得到一个错误。

您只能在翻译单元中定义一次函数。内联函数也不例外(它们确实在链接在一起的单独 TU 中定义时出现异常)。

您应该做的是将函数定义移动到它自己的头文件中,然后将其包含在原来的 2 个头文件中。然后你可以在新文件中放置一个 header guard,这样函数只会在第一次被包含时被定义。