1

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;
wazz
  • 4,953
  • 5
  • 20
  • 34
Michael Grinnell
  • 922
  • 1
  • 12
  • 32
  • See https://stackoverflow.com/q/6887471/2785528. – 2785528 Oct 12 '19 at 19:37
  • Technically it can be possible by using the dynamic linker. For example on the Linux platform using `dlsym`: http://coliru.stacked-crooked.com/a/9af85973cd1b7d45 – tmlen Oct 12 '19 at 20:34

3 Answers3

5

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.

Mateusz Stefek
  • 3,478
  • 2
  • 23
  • 28
2

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);
max66
  • 65,235
  • 10
  • 71
  • 111
1

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

AndersK
  • 35,813
  • 6
  • 60
  • 86