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

标签 c++ templates inline

我有两个内容相同的头文件:

template<typename T> inline void func(){

}

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

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

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

最佳答案

你错过了一个关键部分。该标准在 [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[...]

强调我的

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

关于c++ - 如果我在 C++ 中使用内联函数,为什么会重新定义“template<class T>”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44308216/

相关文章:

C++ 将 std::initializer_list 强制为模板函数中的容器

c++ - 尽管有 cin.ignore(),但 Cin 没有等待输入

c++ - 模板特化 vs 在模板参数类型上使用 if else

c++ - 为什么编译器在下面的例子中没有选择我的函数模板重载?

c++ - 为模板类嵌套类定义 std::hash 的编译错误

kotlin - 为什么 `Intrinsics.checkParameterIsNotNull` 没有内联?

css - 如何使用 CSS 模拟表格单元格(无 float )?

c++ - 创建仿函数时友元函数的可见性

c++ - 通过数学引用传递

C++隐式内联函数