Re: Multiple definitions of specialized template member function
On 7/24/07 12:25 PM, in article 5gmm87F3h2l1vU1@mid.uni-berlin.de, "Ulrich
Eckhardt" <doomster@knuut.de> wrote:
Dariusz Bismor wrote:
[...]
So where is the fault? Because the code I've posted does not compile
unless I precede specialized version with "inline" keyword.
Since it is not inline, inclusion of this header in multiple translation
units results in linker errors. There is nothing that should somehow
magically make it different than other functions or that the inlinedness
was inherited from the non-specialised version of the function.
The original poster was no doubt expecting an explicit specialization of a
function template to treated as a template (for which "inline" is optional
when defined in a header file) - instead of as a function (for which
"inline" is required when defined in a header file).
In your original posting you said "general version may be inline or not".
This BTW is not true. The difference is that for a template, no code is
generated unless(!) it is used. So, if you make it non-inline, too, and
include the header in several TUs and cause instantiation of the template
for the same(!) type, you should get the same error.
No, the original poster is correct: the multiple definition error occurs
only when the non-inline explicit specialization of the function template is
included multiple times. A non-inline general function template, in
contrast, may be included by any number of source files - without causing
any link error at all. The difference between the two is simply the
difference between a function template and a function (which is what an
explicit specialization really is). Here are some sample declarations to
help illustrate this difference:
// FileC.h
class C
{
public:
C();
template <typename T>
void foo( const T& x );
};
template <class T>
void C::foo( const T& x )
{
// OK - non-inline general template definition
}
template <>
void C::foo<double>(const double& x )
{
// Error - multiple C::foo<doubld> definitions at link time
}
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]