0

I've got a multi-file project that uses templates.

// Foo.h
template <class T>
class Foo
{
    T bar;
};

I have a class (e.g. Cup) and a bunch of subclasses of that class.

// Cup.h
class Cup
{
};

class Chalice : public Cup
{
};

class SippyCup : public Cup
{
};

// ...etc.

In the template's .cpp file, I need to list all possible template implementations to avoid linker errors. I learned this from the C++ FAQ.

//Foo.cpp
template class Foo<Cup>;
template class Foo<Chalice>;
template class Foo<SippyCup>;
// ...etc.

In reality, I have about 20+ subclasses that I'd like to use at any point in my code. In development, I'm constantly creating new subclasses. So each time I create a new one, I have to add it to this growing list in Foo.cpp.

This is a pain. Is there a way to get around having to list all of these possibilities?

ryantuck
  • 6,146
  • 10
  • 57
  • 71
  • 4
    "In the template's .cpp file..." Stop right there, and [read this article](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – WhozCraig Aug 23 '13 at 18:34
  • Is there a reason you don't want the definitions in the header? – jrok Aug 23 '13 at 18:37
  • Link above is super helpful and relevant. The only reason to not put the definitions in the header is aesthetics. But it's definitely preferable to listing them all in the cpp file. – ryantuck Aug 23 '13 at 18:55

2 Answers2

4

The way to avoid it is to put the template function definitions in the header file (i.e. in the actual template definition) rather than in a separate .cpp file.

Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
  • I also tried using the method described [here](http://stackoverflow.com/questions/5467785/circular-inclusion-with-templates) using a .tpp file. Thanks. – ryantuck Aug 23 '13 at 18:53
0

Well the Foo class definitions without any template specialization needs to be there inside the .h file (or the .tpp file like its said in the link above). However, the template specialized class definitions need to be defined in the .cpp file with a forward declaration of that type in your .h file(or .tpp file). So for example you want to have a different template class definition for Cup thens

// Foo.h
template <class T>
class Foo
{
  T bar;
};

template<> class Foo<Cup>;

and then you can have a different declaration of this specialized form of the template class inside the same header file or different header files. All the template member functions and constructors of the templated (non-slecialized representation) of the class should be inside the .h file(or .tpp file) but the constructor for the Cup specialized template class has to be inside a .cpp file to avoid linker errors. Also all the non-templated member functions for both the non-specialized and specialized template class have to be defined in the .cpp file if they are not inline :) . Hope this helps!!!!

Shubham
  • 352
  • 3
  • 14