如何在 C++ 中按名称(std::string)调用函数?

2021-12-07 00:00:00 function string c++ invoke code-cleanup

我想知道是否有一种简单的方法可以从字符串中调用函数.我知道一个简单的方法,使用if"和else".

I wonder if there is a simple way to call a function from a string. I know a simple way, using 'if' and 'else'.

int function_1(int i, int j) {
    return i*j;
}

int function_2(int i, int j) {
    return i/j;
}

...
...
...

int function_N(int i, int j) {
    return i+j;
}

int main(int argc, char* argv[]) {
    int i = 4, j = 2;
    string function = "function_2";
    cout << callFunction(i, j, function) << endl;
    return 0;
}

这是基本方法

int callFunction(int i, int j, string function) {
    if(function == "function_1") {
        return function_1(i, j);
    } else if(function == "function_2") {
        return function_2(i, j);
    } else if(...) {

    } ...
    ...
    ...
    ...
    return  function_1(i, j);
}

还有更简单的吗?

/* New Approach */
int callFunction(int i, int j, string function) {
    /* I need something simple */
    return function(i, j);
}

推荐答案

您所描述的称为反射,C++ 不支持它.但是,您可能会遇到一些变通方法,例如在这个非常具体的情况下,您可能会使用 std::map 来映射函数的名称 (std::string对象)到函数指针,如果函数具有相同的原型,这可能比看起来更容易:

What you have described is called reflection and C++ doesn't support it. However you might come with some work-around, for example in this very concrete case you might use an std::map that would map names of functions (std::string objects) to function pointers, which in case of functions with the very same prototype could be easier than it might seem:

#include <iostream>
#include <map>

int add(int i, int j) { return i+j; }
int sub(int i, int j) { return i-j; }

typedef int (*FnPtr)(int, int);

int main() {
    // initialization:
    std::map<std::string, FnPtr> myMap;
    myMap["add"] = add;
    myMap["sub"] = sub;

    // usage:
    std::string s("add");
    int res = myMap[s](2,3);
    std::cout << res;
}

注意myMap[s](2,3)检索映射到字符串s的函数指针并调用这个函数,传递23 到它,使这个例子的输出是 5

Note that myMap[s](2,3) retrieves the function pointer mapped to string s and invokes this function, passing 2 and 3 to it, making the output of this example to be 5

相关文章