Search code examples
c++callstd-function

How to call a function(only known at runtime) with parameter values(only known at runtime)?


At runtime a single test is made to determine which of two functions to call and also to establish parameter value(s).

The function is then called every few seconds.

void Foo::func( std::string s);
void Foo::func( std::string s1 std::string s2, std::string s2);

Obviously, its inefficient to test( which function to call ) for every call, especially when the function and its parameter value(s) will not change once established.

I need something like this:

Test once which function to call and established parameter value(s).

Assign initialised function to some kind of callable variable.

funcVar = void Foo::func( "blah", "blah", "woof" );

or

funcVar = void Foo::func( "blah" );

Then call function;

for( every few seconds )
{
call FuncVar;
}

Is there some kind of callable variable I can use to do this?


Solution

  • You can simply use a lambda function object ( closure ) which you can call as often as you like.

    Example:

    struct Foo 
    {
        void func( std::string s){ std::cout << "single" << s << std::endl; };
        void func( std::string s1, std::string s2, std::string s3) 
        {   
            std::cout << "tripple " << s1 << " " << s2 << " " << s3 << std::endl;
        }   
    
        // Select which function to call
        std::function<void()> Select( int what )
        {   
            if ( what == 1 )
            {   
                // Create a callable object and put in also parameters
                return [this]() { func("Hallo"); };
            }
            else
            {   
                // The same for the other selection
                return [this]() { func("This","is","tripple!"); };
            }
        }   
    };  
    
    int main()
    {   
        Foo foo;
     
        // Pick what you want to select
        auto action = foo.Select( 2 );
    
        for ( ;; )
        {   
            // and call it as often you like
            action();
        }   
    }