Search code examples
c++templateslambdastd-function

Creating a std::function with a lambda without knowing the arguments of the function


I would like to create a std::function from a lambda, in a template that takes the desired instance of std::function as its argument :

template <class functionT>
functionT make_lambda() {
    return [](/* ignore all args */){ std::cout << "my lambda\n"; };
}

And then call that template with varying aliases of std::function :

using function_no_args = std::function<void(void)>;
using function_args = std::function<void(int)>;

make_lambda<function_no_args>()(); // output: "my lambda"
make_lambda<function_args>()(999); // compile error

How can I achieve this ?

Some precisions :

  • I need the ability to have aliases for the std::function, to define them in traits structures and pass them around to multiple portions of my code
  • The return type will always be void, only the arguments may change

Solution

  • Simply use a generic lambda with a parameter pack to swallow and ignore whatever arguments may be given to it:

    template <class functionT>
    functionT make_lambda() {
        return [](auto&&...){ std::cout << "my lambda\n"; };
    }