Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a template function deduce a lambda's arguments?

A templated function that takes a function pointer can deduce the arguments of that function pointer like this:

template<class... Args>
void func(void (*ptr)(Args&& ...)) {
    //Do something useful knowing the Args...
}

Can you do the same with a lambda as the argument; without resorting to std::function or writing a metaprogramming traits class like a function_traits? i.e. deduce the arguments just using a function.

like image 802
Brian Avatar asked May 21 '26 05:05

Brian


1 Answers

No, that's not possible. Template argument deduction can only deduce types, constants, and templates that are "compositionally" part of the argument types, for example, deducing void and Args... from void(*)(Args&&...) as in your example, or deducing T and N from T(&)[N]. It cannot deduce anything that doesn't appear in the type.

For a non-polymorphic lambda type T, the type of &T::operator() contains deducible information about the lambda's argument types. But T itself does not.

like image 120
Brian Bi Avatar answered May 22 '26 18:05

Brian Bi



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!