Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function using a string containing the function's name

Tags:

c++

I have a class defined as

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

};

Is there any way to store this function name inside a string in main function and then call it. I tried this but it's not working.

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(); 
}

I know this is wrong. But I just want to know if there is any way to call a function name using variable.

like image 337
sajal Avatar asked Aug 26 '13 10:08

sajal


2 Answers

This is not directly possible in C++. C++ is a compiled language, so the names of functions and variables are not present in the executable file - so there is no way for the code to associate your string with the name of a function.

You can get a similar effect by using function pointers, but in your case you are trying to use a member function as well, which complicates matters a little bit.

I will make a little example, but wanted to get an answer in before I spend 10 minutes to write code.

Edit: Here's some code to show what I mean:

#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;
}

Of course, if you want to store the functions in a map<std::string, funcptr>, then that is entirely possible.

like image 80
Mats Petersson Avatar answered Oct 17 '22 05:10

Mats Petersson


You have two choices:

1 - manually create a map with pointers to the functions you need and their identifiers as a string key so you can perform lookups, or..

2 - create a dynamic link library/shared object and use name lookup to get the pointer. Use extern "C" to prohibit identifier mangling. You may not be able to use certain C++ features and performance will be slightly worse, depending on your actual usage scenario.

like image 33
dtech Avatar answered Oct 17 '22 04:10

dtech