I want to use a lambda to evaluate (switch-case) some conditions and return a lambda accordingly.
const auto lmb1 = []() {
printf("1\n");
};
const auto lmb2 = []() {
printf("2\n");
};
const auto select = [](auto const &ref) {
switch(ref) {
case 1: return lmb1;
case 2: return lmb2;
}
};
std::function foo = select(1);
foo();
Sadly things aren't working.
What I am doint wrong?
The problem is that a lambda, by default, deduce (as an
autofunction) the returned type and in your lambda you return two different lambdas. Every lambda has a different type, so the compiler can't choose a type for the returned lambdaYou can solve the problem in different ways.
You can explicit the lambda returned type, using a type that both
lmb1andlmb2can be converted to (in this example,std::function<void()>or alsovoid(*)()). When that type is availableYou can explicitly convert the returned values to a common type. Again: when a common type is available
If the
refargument can be a template value, starting from c++20 you can define a template lambda and, usingif constexpr, you can return different types from different lambdas. This works also when there isn't a common type (but require a compile-time known argument)