23
votes
##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.

2
What does func2 have to do with it?Björn Pollex
From your error message I assume you use VC. Your program works fine for me on VS2005mkaes
@Space_C0wb0y So I had something to put in the A.cpp filehidayat
I am using visual studio 2010hidayat

2 Answers

39
votes

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.

15
votes

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