Domanda

I want to pass a type as a parameter (not a variable or a reference).

I have this working code:

execution code where "testState2" is the name of a class (i.e. the type in this case). Note it has a base type of state_t:

changeState(new testState2());

change state function:

void state_t::changeState(state_t * new_state)
{
    // Check if the state has changed
    if (this != new_state)
    {
        qDebug() << this->name << ": State changed to: " << new_state->name;
        delete this;
        _state = new_state;
    }
    else
    {
        qDebug() << this->name << ": State un-changed";
    }
}

In this code I am basically creating a new instance of testState2, but I want to simplify the calling code further. I want to just pass in the type, like this:

    changeState(testState2);

Note: There is no "new" and this is not creating an instance, merely passing the name of the class, so:

  1. Is this even possible?
  2. If so, how?
È stato utile?

Soluzione

Classes (and types in general) in C++ are not first-class values and therefore cannot be passed around or stored.

For classes you can theoretically use typeid but most often I found more useful just having strings returned by a virtual function in instances and a registry to implement a "virtual constructor" pattern.

struct Base
{
    virtual const char *class_name() = 0;
    ...
};

struct MyClass : public(Base)
{
    virtual const char *class_name() { return "MyClass"; }
    ...
}

std::map<std::string, Base *(*)()> instance_builders;

Altri suggerimenti

For learning the State pattern, the example at State Design Pattern in C++ may be a good starting point.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top