Calculation of patterns for lambda variable pattern arguments

Given the following variation pattern:

template<typename... Params> void fun(void(*f)(Params...), Params... params) { f(params...); } int main() { fun(+[](int a, int b) {}, 2, 3); } 

Currently, when calling fun with lambda, I need to explicitly specify the types of all lambda arguments. This seems redundant since int, int can be inferred from 2, 3 . Is there a way to make it more concise and automatic?

I would like the following to work, but it is not:

 template<typename... Params> void fun(void(*f)(Params...), Params... params) { f(params...); } int main() { fun(+[](auto a, auto b) {}, 2, 3); } 

I am compiling with g++ 5.4.0 and -std=c++14 .

+6
source share
1 answer

Take the function T instead of the pointer:

 template<typename T, typename... Params> void fun(T f, Params... params) { f(params...); } int main() { fun([](auto a, auto b) {}, 2, 3); } 

Thus, the compiler can choose which congestion is the right of the call on the call site, and not inside the + operator. As the comment says, in the general case, there is no + operator for universal lambdas.


Alternatively, you can disable the compiler from trying to infer Params from a function pointer using an authentication alias, but I really do not recommend it . Anyway, here you go:

 template<typename T> struct identity { using type = T; }; template<typename T> using identity_t = typename identity<T>::type; template<typename... Params> void fun(void(*f)(identity_t<Params>...), Params... params) { f(params...); } int main() { // v----- no unary +. That operator is not defined for generic lambdas. fun([](auto a, auto b) {}, 2, 3); } 
+3
source

Source: https://habr.com/ru/post/1014928/


All Articles