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

Ala*_*ejo 18 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;
}
Run Code Online (Sandbox Code Playgroud)

这是基本方法

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);
}
Run Code Online (Sandbox Code Playgroud)

有什么比这更简单的了吗?

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

Lih*_*ihO 45

你所描述的是反射,C++不支持它.然而,你可能会想出一些变通,例如在这种非常具体的情况下,你可以使用一个std::map将映射功能(的名字std::string对象)函数指针,它在功能的情况下用非常相同的原型可能是比它更容易似乎:

#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;
}
Run Code Online (Sandbox Code Playgroud)

注意,myMap[s](2,3)检索映射到串的函数指针s并调用此函数,传递23到它,使本实施例的输出是5


Mar*_*ork 21

使用标准字符串到标准函数的映射.

#include <functional>
#include <map>
#include <string>
#include <iostream>

int add(int x, int y) {return x+y;}
int sub(int x, int y) {return x-y;}

int main()
{
    std::map<std::string, std::function<int(int,int)>>  funcMap =
         {{ "add", add},
          { "sub", sub}
         };

    std::cout << funcMap["add"](2,3) << "\n";
    std::cout << funcMap["sub"](5,2) << "\n";
}
Run Code Online (Sandbox Code Playgroud)

使用Lambda更好:

#include <functional>
#include <map>
#include <string>
#include <iostream>

int main()
{
    std::map<std::string, std::function<int(int,int)>>  funcMap =
         {{ "add", [](int x, int y){return x+y;}},
          { "sub", [](int x, int y){return x-y;}}
         };

    std::cout << funcMap["add"](2,3) << "\n";
    std::cout << funcMap["sub"](5,2) << "\n";
}
Run Code Online (Sandbox Code Playgroud)


jav*_*jav 5

您还可以将您的函数放入共享库中。您将使用 dlopen() 动态加载此类库,然后使用 std::string 调用函数。这里有一个例子:

你好.cpp

#include <iostream>

extern "C" void hello() {
    std::cout << "hello" << '\n';
}
Run Code Online (Sandbox Code Playgroud)

主程序

#include <iostream>
#include <dlfcn.h>

int main() {
    using std::cout;
    using std::cerr;

    cout << "C++ dlopen demo\n\n";

    // open the library
    cout << "Opening hello.so...\n";
    void* handle = dlopen("./hello.so", RTLD_LAZY);

    if (!handle) {
        cerr << "Cannot open library: " << dlerror() << '\n';
        return 1;
    }

    // load the symbol
    cout << "Loading symbol hello...\n";
    typedef void (*hello_t)();

    // reset errors
    dlerror();

    std::string yourfunc("hello"); // Here is your function

    hello_t hello = (hello_t) dlsym(handle, yourfunc.c_str());
    const char *dlsym_error = dlerror();
    if (dlsym_error) {
        cerr << "Cannot load symbol 'hello': " << dlsym_error <<
            '\n';
        dlclose(handle);
        return 1;
    }

    // use it to do the calculation
    cout << "Calling hello...\n";
    hello();

    // close the library
    cout << "Closing library...\n";
    dlclose(handle);
}
Run Code Online (Sandbox Code Playgroud)

汇编:

g++ -fPIC -shared hello.cpp -o hello.so
Run Code Online (Sandbox Code Playgroud)

和:

g++ main.cpp -o main -ldl
Run Code Online (Sandbox Code Playgroud)

跑:

C++ dlopen demo

Opening hello.so...
Loading symbol hello...
Calling hello...
hello
Closing library...
Run Code Online (Sandbox Code Playgroud)

这个例子是从这里来的在那里你可以找到关于 dlopen() 和 c++ 的更详细的解释