Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implications of template declaration & definition

Tags:

c++

templates

From what I understand template classes and template functions (for the most part) must be declared and defined in the same header file. With that said:

  1. Are there any other ways to achieve separate compilation of template files other than using particular compilers? If yes, what are those?

  2. What, if any, are the drawbacks of having the declaration and definition in the same file?

  3. What is considered best-practice when it comes to template declaration & definition?

like image 963
Dan Avatar asked Feb 02 '10 16:02

Dan


2 Answers

How To Organize Template Source Code

Basically, you have the following options:

  • Make the template definition visible to compiler in the point of instantiation.
  • Instantiate the types you need explicitly in a separate compile unit, so that linker can find it.
  • Use keyword export (if available)
like image 150
Nemanja Trifunovic Avatar answered Oct 14 '22 23:10

Nemanja Trifunovic


One of the drawbacks encountered by implementing templates in the .h files is that any time you make a small change to the implementation, all the code that uses the template must be recompiled. There's really no way around this aside from not using templates, or declaring & defining them in the CPP file where you use them.

You can implement templates in a seperate file, and then include that file from the .h file. Such as:

templ.h

template<class V> V foo(const V& rhs);
#include "templ.inc"

templ.inc

template<class V> V foo*const V& rhs)
{
// do something...
return val;
}

My personal preference is to implement templates right in the h file unless they become large, and then I'll break it up in to h and inc files.

like image 38
John Dibling Avatar answered Oct 14 '22 23:10

John Dibling