pointer to a function

given:

the function name as a string
need to get a pointer to a function

Please help in the implementation, if it is possible to do
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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).

Here's an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <map>
#include <string>

int foo(double n)
{
    if (n > 0.5)
        return 42;
    else
        return 0;
}

int main()
{
    typedef int (*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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
void foo1()
{
    std::cout << "Hi!" << std::endl;
}
void foo2()
{
    std::cout << "Hello!" << std::endl;
}

int main()
{
    std::cout << "Enter function name: " << std::endl;
    std::string function_name;
    std::cin >> function_name;

   if (function_name == "foo1")
       foo1();
   else if (function_name == "foo2")
       foo2();
   else
       std::cout << "Unknown function" << std::endl;
}
Last edited on
No "built-in", no "portable", but there are POSIX and Windows functions to work with dynamic libraries explicitly. http://www.cplusplus.com/forum/general/114857/


However, I'm not sure what the OP question actually is.
Thanks to all that helped!
Topic archived. No new replies allowed.