Expression of the result type of the ternary conditional `?:`

What do you indicate for the return type for the next function, which should act like ?:, but without laziness?

My first attempt was as follows:

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 this:

int f() { return 42; }
int x = 5;

while

(true ? x : f())++; 

crashes to compile

myif(true, x, f())++;

compiles and returns the link to the link.

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)++

not returning, as now I am returning by value.

Evenly:

auto myif(bool b, T1&& true_result, T2&& false_result) 
  -> typeof(b ? true_result : false_result)

fails, I'm not sure why it might typeofconvert the argument to a value type. In any case, the point should express the type explicitly, and not through autoand typeof.

Any idea how to make a function that returns the same type as ?:?

+4
1

, - :

template <typename T1, typename T2> 
auto myif(bool b, T1&& true_result, T2&& false_result)
    -> decltype(b ? std::forward<T1>(true_result) : std::forward<T2>(false_result))
{
    if (b) {
        return true_result;
    } else {
        return false_result;
    }   
}

++ 14 :

template <typename T1, typename T2> 
decltype(auto) myif(bool b, T1&& true_result, T2&& false_result)
{
    // same body
}

, :

int f() { return 42; }
int x = 5, y = 7;

myif(true, x, f())++; // error: lvalue required as increment operand
myif(false, x, y)++;  // OK
+1

All Articles