What do you specify the return type to be for the following function which should act like ?:
but without the laziness?
My first attempt was the following:
template <typename T1, typename T2>
T1 myif(bool b, T1&& true_result, T2&& false_result)
{
if (b) {
return true_result;
} else {
return false_result;
}
}
But then I found given:
int f() { return 42; }
int x = 5;
whilst
(true ? x : f())++;
falls to compile,
myif(true, x, f())++;
compiles fine and returns a dangling reference.
My second attempt was to change the return type to:
typename std::remove_reference<T1>::type
but then
(true ? x : x)++
works, but:
myif(true, x, x)++
does not as I'm returning by value now.
Even:
auto myif(bool b, T1&& true_result, T2&& false_result)
-> typeof(b ? true_result : false_result)
fails, I'm not sure why, perhaps typeof
converts it's argument to a value type. In any case the point was to express the type explicitly, not through auto
and typeof
.
Any idea how to make a function that returns the same type as ?:
?