表达三元条件`?:`的结果类型

时间:2015-02-05 16:44:22

标签: c++ templates c++11 c++14

你为以下函数指定了什么样的返回类型,它应该像?:那样但没有懒惰?

我的第一次尝试如下:

template <typename T1, typename T2>
T1 myif(bool b, T1&& true_result, T2&& false_result)
{
    if (b) {
        return true_result;
    } else {
        return false_result;
    }
}

但后来我找到了:

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

同时

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

要编译,

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

编译好并返回一个悬空参考。

我的第二次尝试是将返回类型更改为:

typename std::remove_reference<T1>::type

但是

(true ? x : x)++

有效,但是:

myif(true, x, x)++

现在不按价值返回。

偶:

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

失败了,我不确定为什么,也许typeof将它的参数转换为值类型。无论如何,要点是明确表达类型,而不是通过autotypeof

知道如何创建一个返回与?:相同类型的函数吗?

1 个答案:

答案 0 :(得分:1)

我认为最好的方法是Casey提出的建议:

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;
    }   
}

其中,在C ++ 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