3

I'm required to have a class "LinkedSortedList" that is a child of "SortedList". SortedList is a template class, so how can I have a child that isn't also a template? The only issue here is that I need to have both LinkedSortedList.h and .cpp, but apparently you cannot leave the definitions for a template in a .cpp, they must be defined with the method/function declarations inside the .h, so I wouldn't have a LinkedSortedList.cpp....or am I just being a complete idiot?

2 Answers2

2

Well lets assume that your LinkedSortedList is only to work with type int (otherwise it would need to be a template it self).

First the compiler needs to know that SortedList<int> must be compiled at the time when sorted_list.cpp (or whereever the template is implemented) is available. Once it is compiled the linker will find it and be able to successfully link it.

So in linked_sorted_list.h you would have something like:

#include "sorted_list.h"

class LinkedSortedList : public SortedList<int> {
   ...
}

In sorted_list.cpp, at the end you must include this line:

template class SortedList<int>;

Alternatively (and that is the better way) you can put the definition of the template into a file with special extention (I tend to you use .icc) that gets included in sorted_list.h:

template <class type>
class SortedList { 
   ...
}

#include "sorted_list.icc"

Now you can compile any types of sorted lists on the fly.

d_inevitable
  • 4,381
  • 2
  • 29
  • 48
0

You can only derive from a fully-defined class, not a class template. This means the code

    template <class C>
    struct A{};
    struct B : public A{};

is invalid. However, both

    struct B : public A<int>{};
    template <class C>
    struct B : public A<C>{};

are valid. So it looks like you'll be stuck with templates. If you really want to have a .cpp file you can move your code into a .cpp and then include it in your .h file (after your class definition). I don't really recommend it because (IMO) it obfuscates your code.

SirGuy
  • 10,660
  • 2
  • 36
  • 66
  • You can define the body of template methods outside of the class definition as follows: template class Printer { void print(); }; template void Printer::print() { ... } It is common to put these definitions in a separate file, and they _must_ be included at the end of your header. Since they are not compiled, the typical naming convention for the inline definitions of foo.h is foo_inl.h – Thomas Bouldin Apr 10 '12 at 02:23
  • I realize you can define your member functions outside your class body, but I've never seen them defined in a separate file. I guess it's not unreasonable to do, just a matter of preference really – SirGuy Apr 10 '12 at 02:29