Suppose I want to create my own lambda key with the following syntax:
auto s = make_switch(std::pair{0, []{ return 0; }}, std::pair{1, []{ return 50; }}, std::pair{2, []{ return 100; }}); assert( s(0) == 0 ); assert( s(1) == 50 ); assert( s(2) == 100 );
I would like to use the fold expression to have a concise implementation that does not require recursion. The idea is to generate something similar to a bunch of nested if :
if(x == 0) return 0; if(x == 1) return 50; if(x == 2) return 100;
I would like to write the following:
// pseudocode template <typename... Pairs> auto make_switch(Pairs... ps) { return [=](int x) { ( if(ps.first == x) return ps.second(), ... ); }; }
The above code does not work because if(...){...} not an expression. Then I tried using the && operator:
template <typename... Pairs> auto make_switch(Pairs... ps) { return [=](int x) { return ((ps.first == x && ps.second()), ...); }; }
This compiles, but returns the result ps.first == x && ps.second() , which is the bool value, not the int value I want.
I would like some operator to be a combination between the comma operator and && : it should evaluate and evaluate on the right side of the operator if the left side evaluates to true .
I cannot come up with any method that would allow me to implement it in such a way as to get the return value of ps.second() and pass it to the calling lambda element returned by make_switch .
Is it possible to implement such a โcascading if s templateโ with the expression fold? I would like to evaluate only as many expressions as required until an appropriate branch is found.
c ++ fold c ++ 17
Vittorio romeo
source share