Calling a function with a dynamically defined name

Is there a way to call a function whose name is defined in a file-stored-list?

In other words: The caller doesn't know in compile time the name of the function.

I'm not talking about polymorphism.

The problem is: I have a list of function names stored in a file, that may change every now and then, and I'd like to call them in the sequence they appear in that list.

Thanks in advance

Alfredo
Use a lookup table which maps function names (in the file) to callable objects.

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <unordered_map>
#include <functional>
#include <string>
#include <iostream>

int foo( int a ) { std::cout << "foo\n" ; return a*2 ; }

struct A
{
    bool bar( int x, int y ) { std::cout << "A::bar\n" ; return x+y+z > 100 ; }
    int z = 7 ;
};

auto lambda = [] ( double d ) { std::cout << "lambda\n" ; return d+5 ; } ;

int main()
{
    A a ;
    std::unordered_map< std::string, std::function< void(void) > > look_up =
    {
        { "FUNC_1", std::bind( ::foo, 20 ) },
        { "FUNC_2", std::bind( &A::bar, a, 20, 30 ) },
        { "FUNC_3", std::bind( std::multiplies<int>(), 20, 30 ) },
        { "FUNC_4", std::bind( lambda, 2.3 ) }
    };

    std::string fn_name ;
    while( std::cout << "function name? " && std::cin >> fn_name )
    {
        auto iterator = look_up.find(fn_name) ;

        if( iterator == look_up.end() )
            std::cerr << "lookup of function " << fn_name << " failed\n" ;

        else
        {
            std::cout << "calling function " << fn_name << '\n' ;
            (iterator->second)() ;
        }
    }
}



Last edited on
JLBorges

Many thanks for your speedy answer.
It solved my problem
Topic archived. No new replies allowed.