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?
To have all the information available, current compilers tend to require that a template must be fully defined whenever it is used. That includes all of its member functions and all template functions called from those. Consequently, template writers tend to place template definition in header files.
A header file is a file containing C declarations and macro definitions (see Macros) to be shared between several source files. You request the use of a header file in your program by including it, with the C preprocessing directive ' #include '. Header files serve two purposes.
A template is not like a function which can be compiled into byte code. It is just a pattern to generate such a function. If you put a template on its own into a *. cpp file, there is nothing to compile.
A header file should be included only when a forward declaration would not do the job. The header file should be so designed that the order of header file inclusion is not important. This is achieved by making sure that x.h is the first header file in x.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With