Answer the question
In order to leave comments, you need to log in
C++ list of references to functions that return new instances of heterogeneous classes?
How can functions be called by references from handlers in such code? Or have I screwed up a lot with this?
namespace RequestHandlers
{
class Base
{
public:
virtual Response* processing(Request* request);
};
class Info : public Base
{
};
class List : public Base
{
};
}
template<class T>
T* createInstance()
{
return new T();
}
QMap<unsigned int, void*> handlers;
handlers[1] = &createInstance<RequestHandlers::Info>;
handlers[2] = &createInstance<RequestHandlers::List>;
//handlers[1]() вызывает ошибку
Answer the question
In order to leave comments, you need to log in
What mistake?
createInstance returns a pointer, and you take its address and write it to handlers. Are you going to call the pointer?
As a result, this is the code. Maybe there is a way to somehow implicitly add new types? Those. get rid of the explicit call to Base::registerType().
class Info : public Base
{
};
class List : public Base
{
};
Base::registerType<Info>();
Base::registerType<List>();
Base::createInstance(1)->processing(new Request);
You can add a static initializer to each class.
class bar : public Base
{
public:
// ...
class registrator {
public:
registrator()
{
Base::registerType<bar>();
}
};
static registrator _registrator;
};
bar::registrator bar::_registrator;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question