Creating a New Object with Parameter

advertisements
void ChangeState(int newState)
{
    nextState = newState;

    //Change the state
    switch( nextState ) ///the change still will have a case for everything
    {
    case STATE_INTRO:
    {
        vec.pop_back();
        state ptr(new CIntroState);
        vec.push_back(ptr);
        break;
    }
    case STATE_MENU:
    {
        vec.pop_back();
        state ptr(new CMainMState);
        vec.push_back(ptr);
        break;
    }
    }
}

I have this function that allows me to change my current state; however, I thought about it and this is going to be a huge switch statement by the time I am finished. Currently, it already has about 10 states in it, this is just some sample code. I am trying to do something a little different, but I am not sure how to go about it.

void ChangeState(something)
{
    vec.pop_back();
    state ptr(new something);
    vec.push_back(ptr)
}

If I could bring it in this way, I could completely avoid the use of the switch statement and get the same end result. Does anyone know how to go about this? Any help would be greatly appreciated.


You need to link compile-time polymorphism (i.e., templates) and run-time polymorphism, as ryanbwork suggests. The challenge here is to try to avoid transforming your current form of repetitive code (the big switch) into a similarly verbose but more declarative form of repetitive code.

As another popular Stack Overflow question reveals, clone methods are usually the way one creates new instances of dynamically determined types at run-time. Cloning is really a specialization of the more general factory pattern, and you could create a set of factories for your types whose definition would be only a little more verbose than your current enumeration presumably is:

template <class T>
class factory {
public:
   T* operator()() {return new T;}
};

factory<CIntroState> IntroState;
factory<CMainState>  MainState;
// etc...

template <class Fac>
void ChangeState(Fac newStateFactory)
{
   vec.pop_back();
   vec.push_back(newStateFactory());
}