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

房东的猫 提交于 2020-01-17 06:44:41

问题


I have 2 header files that have identical content:

template<typename T> inline void func(){

}

I include these 2 headers in a main.cpp file then I compile:

g++ main.cpp -o run

But I get:

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

What am I getting this error if use inline function which can be redefined?


回答1:


You missing a key piece. The standard says in [basic.def.odr]/6 that

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[...]

emphasis mine

So, you're allowed to have have multiple definitions of the inline function, but those definitions need to be in separate translation units(basically source files). Since they are in the same translation unit, they are violating that and you get an error.




回答2:


Because of 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.




回答3:


You're only allowed to define a function once in a translation unit. There's no exception for inline functions (they do get an exception for being defined in separate TUs that are linked together).

What you should do is move the function definition to its own header file, which then gets included by the original 2 headers. Then you can put a header guard in the new file, so the function only gets defined the first time it's included.



来源:https://stackoverflow.com/questions/44308216/why-am-i-getting-redefinition-of-templateclass-t-if-i-use-inline-function-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!