ae8bna
Last Updated: February 25, 2016
·
5.333K
· ysgard

Template implementation in .cpp file

When crafting a new template class, you can place the implementation of the class within a separate cpp file as long as you create a trivial instantiation of that class within it.

Usually the template class methods are implemented within the header:

// foo.h
#ifndef FOO_H
#define FOO_H

template<typename T> class Foo {
    public:
    Foo(T bar);
};

template<typename T> Foo<T>::Foo(T bar) {}

#endif

For large template classes, this can result in unwieldy header files. But you can separate out the method implementations into a separate cpp file if you do this:

// foo.h
#ifndef FOO_H
#define FOO_H

template<typename T> class Foo {
    public:
    Foo(T bar);
};

#endif

// foo.cpp

#include "foo.h"

template<typename T> Foo<T>::Foo(T bar) {}

// At end of file
template class HeapTree<int>;  // Explicit instantiation