在C++中,如何选择在不使用if语句的情况下运行特定的成员函数?

Spa*_*cey 2 c++ constructor if-statement class member

我想了解是否存在一种"优雅"方式,可以根据用户输入选择运行特定(c ++)类成员函数.

例如,让我们说我们有一个类,这样:

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


    void function1();
    void function2();
};
Run Code Online (Sandbox Code Playgroud)

我想做的是,如果用户input=1在构造函数中指定,则function1()在调用runMyFunction()成员时调用,但如果用户input=2在构造函数中指定,function2()则应调用.

我的问题是,有没有更优雅的方式去做这个没有if声明?推动力是我宁愿让代码一遍又一遍地通过这个检查,因为我将在循环中使用这个调用.if在这种情况下,是否有更优雅的方式来"设置"在没有语句的情况下调用哪个函数?谢谢.

Mar*_*ork 5

是的,您可以使用命令模式.您只需要设置一个函数方法指针数组.

std::vector<std::function<void()>>  actionCommand = 
      {[](){}, // Zero based index.
       [this](){this->function1();},
       [this](){this->function2();}
      };

void runMyFunction() 
    { 
        actionCommand[foo]();

        // or 

        actionCommand.at(foo)(); // throws exception if foo is not in
                                 // correct range.
    }
Run Code Online (Sandbox Code Playgroud)