Why the best place to define templates is in header file? (c++)

The C++ standard library: a tutorial and handbook:

The only portable way of using templates at the moment is to implement them in header files by using inline functions.

Why is that?

Because when compiler instantiate the template, it need to access to the implementation of the methods. If it’s not together with it’s declaration, the compiler doesn’t know how to instantiate it. For example:

1
2
3
4
5
template <typename T>
class Foo
{
T a;
}

and when you declare:

1
Foo<double> bar;

The compiler will generate code like this:

1
2
3
4
class Foo
{
double a;
}

There are other ways to achieve this, for example implement it in some .tpp files and include those files after their declaration, as long as compiler can access to the definition of that template.