30

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?

Michael
  • 1,464
  • 1
  • 20
  • 40

2 Answers2

33

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.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • I think you still have to declare the specialization in the header. Otherwise, how does the compiler know to use it, rather than to instantiate the template? – James Kanze Aug 02 '12 at 09:27
  • Right, a specialized function template is just like an "ordinary" function. You have to have at least a declaration to be able to use it. – Bo Persson Aug 02 '12 at 09:31
  • Yes, but I'd add that to your answer, if I were you. As you've written it, it's not clear that a declaration of the specialization is necessary in the header. – James Kanze Aug 02 '12 at 10:01
  • Yes, this is quite dangerous. If you forget the declaration the compiler creates the call from the original template, instead of using the specialisation – Michael Aug 02 '12 at 16:11
  • Can I use `static` instead of `inline`? – tuket Oct 27 '19 at 08:15
12

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.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331