我有两个内容相同的头文件:
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/