Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 774
Fourmet Avatar asked Feb 13 '26 16:02

Fourmet


1 Answers

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"; };
}
like image 168
Michael Kenzel Avatar answered Feb 16 '26 07:02

Michael Kenzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!