Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function template specialization compile error

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

like image 205
hidayat Avatar asked Mar 24 '11 09:03

hidayat


People also ask

What is function template specialization?

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.

Are templates resolved at compile time?

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!

What does template <> mean in C++?

It's a specialization. template<> means that the specialization itself is not templated- i.e., it is an explicit specialization, not a partial specialization.

What is the main problem with templates C++?

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.


2 Answers

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.

like image 179
ildjarn Avatar answered Sep 29 '22 07:09

ildjarn


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

like image 45
Alexander Poluektov Avatar answered Sep 29 '22 06:09

Alexander Poluektov