如何在C ++中通过其名称(std :: string)调用函数? [英] How to call a function by its name (std::string) in C++?

查看:122
本文介绍了如何在C ++中通过其名称(std :: string)调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一个简单的方法来从字符串调用函数。我知道一个简单的方法,使用'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 objects)到函数指针,在使用完全相同的原型的函数的情况下,它可能比看起来更容易:

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] )检索映射到字符串 s 的函数指针并调用此函数,传递 2 3 ,使此示例的输出为 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

这篇关于如何在C ++中通过其名称(std :: string)调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆