问题
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