vendredi 15 mai 2015

In C++, how to choose to run a specific member function without using if-statements?

I would like to understand if there is an 'elegant' way in which one can choose to run a particular (c++) class member function, based on user input.

For example let us say we have a class such that:

class myClass
{
    int foo;
    myClass(int input) { foo = input;}
    void runMyFunction() 
    { 
        if ( foo == 1) 
        {
            function1();
        }
        else if (foo == 2)
        {
            function2();
        } 
    }


    void function1();
    void function2();
};

What I would like to do, is that if a user specifies input=1 in the constructor, then function1() is called when the runMyFunction() member is called, but if the user had specified input=2 in the constructor, then function2() should be called instead.

My question is, is there a more elegant way to go this without an if statement? The impetus is that I would rather not have the code go through this check over and over again, since I will be using this call in a loop. Is there a more elegant way to 'set' which function is going to be called without if statements in this case? Thanks.

Aucun commentaire:

Enregistrer un commentaire