Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do template specialisations belong into the header or source file?

Tags:

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?

like image 900
Michael Avatar asked Aug 02 '12 08:08

Michael


People also ask

Do templates go in header files?

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.

What belongs in a header file?

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.

Why template function only defined header files?

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.

Do I include the header file in a source file?

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.


1 Answers

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.

like image 59
Bo Persson Avatar answered Sep 27 '22 00:09

Bo Persson