#include <iostream>
void foo()
{
std::cout << "foo points to a void function that prints this line." << std::endl;
}
void executeFunc(void (*func)() ) //void=return type; *func=funcname; ()=params
{
func();
}
int main()
{
std::cout << "the name of a function is also a pointer to it!" << std::endl;
std::cout << "need proof? here:" << std::endl;
executeFunc(foo);
std::cout << "boom!";
return 0;
}
The function/variable names inside your source code have no relation to the actual logic of the program, so there isn't a built-in way to make "my_func" as a string point to a function called my_func in the source code.
One way to circumvent this is to use a mapping, std::map. This will map an std::string to a raw function pointer (you can also use std::function if you don't want to work with raw function pointers).
#include <iostream>
#include <map>
#include <string>
int foo(double n)
{
if (n > 0.5)
return 42;
elsereturn 0;
}
int main()
{
typedefint (*FuncPtr)(double); // typedefing function pointer for easy use
// see http://stackoverflow.com/questions/4295432/typedef-function-pointer
// map an std::string to a function that expects a double as input,
// and returns an int:
std::map<std::string, FuncPtr> mapping;
mapping["foo"] = foo; // Add item to map
// Call the function through the mapping:
std::cout << mapping["foo"](0.6) << std::endl;
}
The other alternative would be to just have an if-else chain: