function template specialization compile error

一世执手 提交于 2019-12-21 03:33:35

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/5417215/function-template-specialization-compile-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!