Search code examples
c++lambdastd-function

Class method accepting lambdas representing functions of various number of argument


I would like to pass functions in to a generic class method, so the generic class can invoke functions requiring no args, one arg, two args etc.

I have seen variadic templates but I do not like the syntax. A previous SO question recommended passing lambdas, wrapping the function:

https://stackoverflow.com/a/48976528/997112

where the answer is:

void run_callback(std::function<void()>& func) 
{
    func();
}

run_callback([]{ func_without_params(); });

and I therefore added a method which requires no argument:

void func_without_params()
{
    std::cout << "x" << std::endl;
}

but when I call:

run_callback([]{ func_without_params(); });

in VS2013 the intellisense detects an error and i get the compiler error:

error C2664: 'void run_callback(std::function<void (void)> &)' :
cannot convert argument 1 from
'main::<lambda_de925f4d5cd926a8bb664f9c057a7a19>' to
'std::function<void (void)> &'

What is a main::<lambda_de925f4d5cd926a8bb664f9c057a7a19> type? I don't fully-understand the error.


Solution

  • Except for evil compiler extensions you cannot initialize a non-const reference (parameter func) with something that is not an l-value. Make the parameter const:

    #include <functional>
    #include <iostream>
    
    void run_callback(std::function<void()> const &func)
    {
        func();
    }
    
    void func_without_params()
    {
        std::cout << "x" << std::endl;
    }
    
    int main()
    {
        run_callback([] { func_without_params(); });
    }