Marcelo Cantos
Marcelo Cantos

Reputation: 186118

Match variadic template args to lambda parameters

I want to write a function that you call like so:

f("a", 1,                 [](float a                  ) { … });
f("a", 1, "b", 2,         [](float a, float b         ) { … });
f("a", 1, "b", 2, "c", 3, [](float a, float b, float c) { … });

What the function does is immaterial. The point is that each pair of char*/integer parameters to f corresponds to a float parameter to the lambda function. I get as far as this:

template <typename ...Args>
void f(Args... args, std::function<void(???)> cb);

How can I declare the functor type so that the cardinality of its parameters matches the cardinality of the input pairs?

Upvotes: 1

Views: 896

Answers (1)

kennytm
kennytm

Reputation: 523784

When requiring a function object argument, typically you should just allow the function to accept any type, and let the compiler emit the errors automatically when the type actually mismatch.

template <typename... Args, typename F>
void f(const F& func, Args&&... args) { ... }

(Note that I have moved the function argument to the front, because the variadic part will consume all arguments otherwise.)

Upvotes: 2

Related Questions