c++ - 使用包含函数名称的字符串调用函数

标签 c++

我有一个类定义为

class modify_field 
{
    public:
        std::string modify(std::string str)
        {
            return str;
        }

};

有什么方法可以将此函数名称存储在 main 函数的字符串中,然后调用它。 我试过了,但没用。

int main()
{
modify_field  mf;
std::string str,str1,str2;
str = fetch_function_name(); //fetch_function_name() returns string modify
str2 = "check";
cout << str; //prints modify
str1 = str + "(" +str2 + ")";
mf.str1(); 
}

我知道这是错误的。但我只想知道是否有任何方法可以使用变量调用函数名。

最佳答案

这在 C++ 中是不可能直接实现的。 C++ 是一种编译语言,因此函数和变量的名称不存在于可执行文件中 - 因此代码无法将您的字符串与函数名称相关联。

您可以通过使用函数指针获得类似的效果,但在您的情况下,您还尝试使用成员函数,这会使事情变得有点复杂。

我会举一个小例子,但想在我花 10 分钟写代码之前得到答案。

编辑:这里有一些代码来说明我的意思:

#include <algorithm>
#include <string>
#include <iostream>
#include <functional>

class modify_field 
{
public:
    std::string modify(std::string str)
        {
            return str;
        }

    std::string reverse(std::string str)
        {
            std::reverse(str.begin(), str.end());
            return str;
        }
};


typedef std::function<std::string(modify_field&, std::string)> funcptr;


funcptr fetch_function(std::string select)
{
    if (select == "forward")
        return &modify_field::modify;
    if (select == "reverse")
        return &modify_field::reverse;
    return 0;
}



int main()
{
    modify_field mf;

    std::string example = "CAT";

    funcptr fptr = fetch_function("forward");
    std::cout << "Normal: " << fptr(mf, example) << std::endl;

    fptr = fetch_function("reverse");
    std::cout << "Reverse: " << fptr(mf, example) << std::endl;
}

当然,如果您想将函数存储在 map<std::string, funcptr> 中,那么这是完全可能的。

关于c++ - 使用包含函数名称的字符串调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18442101/

相关文章:

c++ - 错误 C2061 在 vi​​sual studio 中

c++ - 如果我在 Linux 上更改 C++ 动态共享库,而我的可执行程序在其上使用,会发生什么

c++ - 共享指针的 copy-and-swap 效率

c++ - 基于堆栈的缓冲区溢出

Code Complete 关于封装的 C++ 建议?

c++ - 空的 "else"是否需要任何时间

c++ - 如何在C/C++中计算最多1000位的数字的位数

c++ - std::function 是否允许在其返回类型中从引用到拷贝进行隐式转换?

c++ - 我的 C++ DLL 无法编译,除非我第一次打开项目(在 Netbeans 中)

c++ - g++ -Wl,-z,nocopyreloc 重定位错误