Thursday, March 8, 2018

c++ - Inlining a function template specialization




The following code is in a .h file (with include guards)



template // a
void func(T1 const &t1, T2 const &t2)
{
std::cout << "\nbase template";
}

template<> // b
inline void func(int const &t1, int const &t2)

{
std::cout << "\nspecialization for integers";
}


When removing the inline keyword from (b) the following code (called from a .cpp that includes the .h) won't compile



func(1, 2);



emmiting a linker error " error LNK2005: "void __cdecl func(int const &,int const &)" (??$func@HH@@YAXABH0@Z) already defined in ConsoleApplication1.obj "



Why is this happening ?



EDIT:



So since they are definitions (answered by Luchian Grigore), do explicit specializations imply explicit instantiation or is this compiler specific?


Answer



Because explicit specializations are definitions and so including that file in multiple translation units results in defining the symbol multiple times, which breaks the one definition rule.




Besides marking it inline, you can leave the declaration in the header and move the definition to an implementation file.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...