Do template specialisations belong into the header or source file?

谁说胖子不能爱 提交于 2019-12-12 09:29:28

问题


During compilation I get a "multiple definition" error, which refers to a template specialisation in a header file. Do I need to put the specialisations into the source file?


回答1:


If it is functions you have specialized, you can either put them in the .cpp file, or make them inline in the header.

Like James points out, if you don't make the functions inline, you still have to declare the specializations in the header. Otherwise the compiler doesn't know it has to look for them elsewhere.

You can then put the implementations (definitions) in a .cpp file. Just like with other functions.




回答2:


No, you don't need to put specializations in a separately compiled file, but, you need to beware that a specialized function template is just an ordinary function, because it's fully specialized.

As such, it can't be defined in multiple translation units unless it's declared inline.



来源:https://stackoverflow.com/questions/11773960/do-template-specialisations-belong-into-the-header-or-source-file

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