Although you should not inherit from stl containers I will give you the answer with your same example.
When using a function or a class template you have to implement the code in the header file, otherwise, the compiler will not instantiate the right functions. When defining function templates the compiler creates a specific class of the function template for the given class. For example, when you do WList<Rectangle>
the compiler creates an instance of the WList
for the template Rectangle
. To do so the compiler needs all the function/class templates in the code that is compiling, otherwise, some functions (the ones that are not in the header file) will be missing and a func is not defined
or undefined reference to func
error happens.
Your code should be something like:
WList.h
#include <list>
template <typename T >
class WList : public std::list<T>
{
public:
void wAdd(T obj)
{
this->push_back(obj);
}
};
or
#include <list>
template <typename T >
class WList: public std::list<T>
{
public:
void wAdd(T obj);
};
template<typename T>
void WList<T>::wAdd(T obj)
{
this->push_back(obj);
}
Main
int main() {
WList<double> list;
list.wAdd(2);
}
A more proper way of doing this would be without inheriting from the stl container:
#include <list>
template <typename T >
class WList
{
public:
void wAdd(T obj)
{
m_data.push_back(obj);
}
protected:
std::list<T> m_data;
};
Moreover, note that using template<typename T>
is better than template<class T>
to avoid static ambiguity between class
as template and class
as class definition