Hello
According to http://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file
it is easy to seprate the interface and the implementation of a template class,
.h file
template<typename T>
class foo
{
public:
foo();
~foo();
void do(const T& t);
};
.cpp file
template <typename T>
void foo::foo()
{
// initiate
}
//destructor
template <typename T>
void foo::do(const T& t)
{
// Do something with t
}
void foo<int> fi;
void foo<std::string> fs;
the trick being to specialise the template class by creating instances at the end of the .cpp file.
But what if this was a pure virtual template class
.h file
template<typename T>
class foo
{
public:
foo();
~foo();
virtual void do(const T& t) = 0;
};
and we derive a concrete class from this:
template<typename T>
class foobar : public foo<T>
{
public:
void do(const T& t);
};
the source file for this class looks like
.cpp file
template <typename T>
void foobar::do(const T& t)
{
// Do something with t
}
void foobar<int> fi;
void foobar<std::string> fs;
and the source file for foo looks the same except the initiations are removed (since ofcourse now foo is an abstract class).
But there's a linker error now; foo<int>()
is unresolved in the constructor of foobar<int>
. This is fixed by moving the constructor and destructor of foo back to the header file from the source file.
So my question is how can we create abstract template base classes and keep the deifnition of the template class hidden in a source file??