S
S
sdevalex2011-12-11 11:37:42
C++ / C#
sdevalex, 2011-12-11 11:37:42

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

3 answer(s)
[
[email protected]><e, 2011-12-11
@sdevalex

What mistake?
createInstance returns a pointer, and you take its address and write it to handlers. Are you going to call the pointer?

S
sdevalex, 2011-12-11
@sdevalex

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);

R
rtorsten, 2011-12-11
@rtorsten

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;

Usually, a macro is written for this (more precisely, 2 macros, the 1st for defining the registrar, the 2nd for defining a static object), because initializers like this need to be added to every class that you want to implicitly register.
And do not forget (maybe you have not forgotten) in Base or what handlers inherit from there add a virtual destructor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question