According to
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
class foo
{
public:
foo();
~foo();
void do(const T& t);
};
.cpp file
template
void foo::foo()
{
// initiate
}
//destructor
template
void foo::do(const T& t)
{
// Do something with t
}
void foo fi;
void foo 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
class foo
{
public:
foo();
~foo();
virtual void do(const T& t) = 0;
};
and we derive a concrete class from this:
template
class foobar : public foo
{
public:
void do(const T& t);
};
the source file for this class looks like
.cpp file
template
void foobar::do(const T& t)
{
// Do something with t
}
void foobar fi;
void foobar 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
is unresolved in the constructor of foobar
. 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??
Answer
You can explicitly instantiate a type without needing to instantiate a variable. Also, your existing code is hideously bugged and doesn't even come close to compiling.
template
class foo
{
public:
foo();
~foo();
void something(const T& t);
};
template
foo::foo()
{
// initiate
}
//destructor
template
void foo::something(const T& t)
{
// Do something with t
}
template
foo::~foo() {
}
template class foo;
This will instantiate foo for int as a type but you don't need to mess around with variables.
No comments:
Post a Comment