##A.hh
template<class T> void func(T t) {}
template<> void func<int>(int t) {}
void func2();
##A.cpp
void func2() {}
##main.cpp
func("hello");
func(int());
The error I get is: error LNK2005: "void __cdecl func(int)" (??$func@H@@YAXH@Z) already defined in A.obj, one or more multiply defined symbols found
Is a function template specialization not treated as a normal function template? It looks like it will be in the objective file for A.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
All the template parameters are fixed+known at compile-time. If there are compiler errors due to template instantiation, they must be caught at compile-time!
It's a specialization. template<> means that the specialization itself is not templated- i.e., it is an explicit specialization, not a partial specialization.
C++ templates can't use normal run-time C++ code in the process of expanding, and suffer for it: for instance, the C++ factorial program is limited in that it produces 32-bit integers rather than arbitrary-length bignums.
As template<> void func<int>(int t) {}
is a function overload rather than a function template (i.e., all types are known at the point of definition so it is no longer a template), it must be marked as inline
or defined in a .cpp file to avoid multiple definition errors, just as with any other function definition.
The problem is as follows: full template specialization is no more a template, it's more like an ordinary function. So you should act accordingly:
either put definition of func<int>()
in cpp file
or make it inline
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With