B
Ben Pope
Hi all,
This is not something I've played around with much, but I'm designing
some factories and I want a function like this:
template<class T>
T* Creator() {
return new T;
}
So that I could store a pointer to an instance in a map along with a
string Id.
Now, the things I want to return would be polymorphic, and so I would
make use of covariant return types. The problem I ran into was
something like the following:
struct Base { virtual ~Base(){} };
struct Derived : Base {};
typedef Base* (*BaseFuncPtr)();
typedef Derived* (*DerivedFuncPtr)();
Base* CreateBase() { return new Base; }
Derived* CreateDerived() { return new Derived; }
int main()
{
// Covariant return types
Base* b(CreateDerived());
// Fine
BaseFuncPtr bfp(&CreateBase);
// Cannot convert?
BaseFuncPtr dfp(&CreateDerived);
}
Although the function pointers are to different types, the type being
returned is polymorphic and covariant. Can somebody just explain why
this doesn't work? Am I expecting too much?
Cheers for any insights,
Ben Pope
This is not something I've played around with much, but I'm designing
some factories and I want a function like this:
template<class T>
T* Creator() {
return new T;
}
So that I could store a pointer to an instance in a map along with a
string Id.
Now, the things I want to return would be polymorphic, and so I would
make use of covariant return types. The problem I ran into was
something like the following:
struct Base { virtual ~Base(){} };
struct Derived : Base {};
typedef Base* (*BaseFuncPtr)();
typedef Derived* (*DerivedFuncPtr)();
Base* CreateBase() { return new Base; }
Derived* CreateDerived() { return new Derived; }
int main()
{
// Covariant return types
Base* b(CreateDerived());
// Fine
BaseFuncPtr bfp(&CreateBase);
// Cannot convert?
BaseFuncPtr dfp(&CreateDerived);
}
Although the function pointers are to different types, the type being
returned is polymorphic and covariant. Can somebody just explain why
this doesn't work? Am I expecting too much?
Cheers for any insights,
Ben Pope