c++ - Is there a std::function type or similar for lambda with auto parameter? -
when assign lambda explicitly typed variable (for example when recursive, capture function in itself), use std::function.
consider silly "bit counting" function example:
std::function<int(int)> f; f = [&f](int x){ return x ? f(x/2)+1 : 0; }; what case when use auto parameter generalize x, introduced in c++14 generic lambda?
std::function<int(???)> f; f = [&f](auto x){ return x ? f(x/2)+1 : 0; }; obviously, can't place auto in function type parameters.
is there possibility define functor class generically enough cover exact case above, still using lambda function definition?
(don't over-generalize this, accept single auto parameter , hard-code return value.) use case scenario above: capturing function in reference recursive calls.
you can create lambda calls passing parameter:
auto f = [](auto self, auto x) -> int { return x ? self(self, x / 2) + 1 : 0; }; std::cout << f(f, 10); you can capture lambda in lambda, don't have worry passing itself:
auto f2 = [&f](auto x) { return f(f, x); }; std::cout << f2(10);
Comments
Post a Comment