Should the child of a template class also be a template class?
I must have a "LinkedSortedList" class that is a child of the "SortedList". SortedList is a template class, so how can I get a child that is also not a template? The only problem here is that I need to have both LinkedSortedList.h and .cpp, but apparently you cannot leave definitions for the template in .cpp, they have to be defined using method / function declarations inside .h, so I wouldn't have LinkedSortedList.cpp .... or am I just a complete idiot?
source to share
Well, let's assume yours LinkedSortedList
only works with a type int
(otherwise it should have been its template).
First, the compiler needs to know what SortedList<int>
should be compiled at the moment sorted_list.cpp
(or regardless of whether the template has been implemented). Once compiled, the linker will find it and can successfully link it.
So, in linked_sorted_list.h
you you will have something like:
#include "sorted_list.h"
class LinkedSortedList : public SortedList<int> {
...
}
At the sorted_list.cpp
end, you must include this line:
template class SortedList<int>;
Alternatively (and this is the best way) you can put the template definition in a file with a special extension (I tend to use it .icc
) that comes in sorted_list.h
:
template <class type>
class SortedList {
...
}
#include "sorted_list.icc"
Now you can compile any sorted list type on the fly.
source to share
You can only get from a fully defined class, not from a class template. This means that the code
template <class C>
struct A{};
struct B : public A{};
wrong. However, both
struct B : public A<int>{};
template <class C>
struct B : public A<C>{};
... It looks like you are stuck with templates. If you really want to have a .cpp file, you can move your code to .cpp and then include it in your .h file (after you define your class). I don't recommend it because (IMO) it obfuscates your code.
source to share