c++ - 如何在 C++ 中通过名称 (std::string) 调用函数?

标签 c++ string function invoke code-cleanup

我想知道是否有一种简单的方法可以从字符串中调用函数。我知道一个简单的方法,使用“if”和“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对象)到函数指针,如果函数具有完全相同的原型(prototype),这可能比看起来更容易:

#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

关于c++ - 如何在 C++ 中通过名称 (std::string) 调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26865980/

相关文章:

javascript - 什么是多种类型原型(prototype)的更好方法

c# - "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions"错误

regex - 在 Perl 中的条件之后计算正则表达式中的字符串

string - 将 System::String^ 转换为 cv::String

r - 在 R 中定义函数内部函数的好方法

Javascript:动态函数名称

c++ - 在放大镜窗口上绘制(放大 API)

c++ - 从 BST 的给定范围插入元素到数组中

c++ - 将一个新 vector 推回一个 vector

c++ - 当一个线程正在编写另一个线程可能同时执行的代码时,如何在 ARM 上进行同步?