Mike Irish
Mike Irish

Reputation: 960

Is there a way to dynamically call functions by their name in c++

I have a list of functions named as so, void F1(), void F2().....

I ask the user to input a number and it will call the corresponding function. So if they input 5 it will call F5().

Rather than having one really long switch statement, I am wondering is there a way to do this by appending the users input to the function call. Something like the below code

std::cout << "Please enter the number of the function you wish to call " << std::endl;

std::cin >> choice;

functionToCall = "F" + choice;

Upvotes: 1

Views: 1457

Answers (3)

AndersK
AndersK

Reputation: 36082

You could do something like this

#include <map>
#include <string>
#include <cmath>

typedef double(*pfunc)(double);
std::map<std::string, pfunc> functionMap_;


functionMap_["acos"] = acos;
functionMap_["cos"] = cos;
functionMap_["asin"] = asin;
functionMap_["sin"] = sin;
functionMap_["atan"] = atan;
functionMap_["tan"] = tan;

to have functions with more arguments you would need maps with other function pointers

typedef double(*p2func)(double, double);
typedef void(RPNCalculator::*spfunc)(void);

and so on

Upvotes: 1

max66
max66

Reputation: 66200

Rather than having one really long switch statement, I am wondering is there a way to do this by appending the users input to the function call.

No.

Not so simple.

The best I can imagine is the use of a std::vector of std::functions (or also function pointers) so you can write something as

vfunc[0] = &F0;
vfunc[1] = &F1;
// ...

auto functionToCall = vfunc[choice]; // or better vfunc.at(choice);

Upvotes: 2

Mateusz Stefek
Mateusz Stefek

Reputation: 3846

No. C++ doesn’t have this kind of reflection.

You can always create a structure which maps strings to function pointers, but you will have to initialize this structure yourself.

Upvotes: 5

Related Questions