Inlining a function template specialization
The following code is in a .h file (with include guards)
template<typename T1, typename T2> // a
void func(T1 const &t1, T2 const &t2)
{
std::cout << "nbase template";
}
template<> // b
inline void func<int, int>(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<int, int>(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?
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.
You can only overloade it directly with the type itself, without the need to write template :
void func(int const &t1, int const &t2)
{
std::cout << "nspecialization for integers";
}
Now, the error happens because that function if defined in a header can end up in two cpp files if the header is included so there will be two declaration of the same function (like the error says: already defined
) causing a linking error. To solve this just write the declaration in the header without the implementation and move the implementation in one of the header files:
//header
void func(int const &t1, int const &t2);
//cpp file
void func(int const &t1, int const &t2)
{
...
}
链接地址: http://www.djcxy.com/p/37138.html
上一篇: C ++
下一篇: 内联函数模板专业化