Re: problems with polymorphism and inheritance with templates
On 29 Aug., 17:47, Frank Buss <f...@frank-buss.de> wrote:
This code:
template<class T>
class Foo
{
public:
T* member;
};
class Base
{
};
typedef Foo<Base> BaseFoo;
class Derived
{
};
In consideration of what you wrote later combined with your
chosen naming conventions, I assume this was actually
meant to be:
class Derived : public Base
{
};
typedef Foo<Derived> DerivedFoo;
int main(int argc, char** argv)
{
DerivedFoo* dfoo = new DerivedFoo();
BaseFoo* bfoo = dfoo;
return 0;
}
doesn't compile, the compiler says "cannot convert ?DerivedFoo*? to
?BaseFoo*? in initialization". How can I fix it? Of course, this one works:
Derived* derived = new Derived();
Base* base = derived;
I know that something similiar (but not really the same) is possible,
because shared_ptr can do it, e.g. this one compiles with g++ 4.3.2:
#include <tr1/memory>
using namespace std::tr1;
class Base
{
};
typedef shared_ptr<Base> BasePtr;
class Derived : public Base
{
};
typedef shared_ptr<Derived> DerivedPtr;
int main(int argc, char** argv)
{
DerivedPtr dptr(new Derived());
BasePtr bptr = dptr;
return 0;
}
It is quite easy to simulate a behaviour that follows
the strategy of shared_ptr, unique_ptr, and similar
classes that can reasonably accept specializations
for different types than the own one. But it is impossible
to "simulate" a base-derived relationship without
introducing such a relation.
The first question is: Why do you need the template,
if you want a specific class hierarchy? Either Foo is
supposed to be some form of a smart pointer, then
there is no reason to create objects in the free store
and to require base-derived relations among smart
pointers. Or Foo is something else, but the question
is: What does it model?
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]