Search code examples
c++templatesinline

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


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?


Solution

  • 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.