【发布时间】:2015-02-05 16:44:21
【问题描述】:
你为下面的函数指定什么返回类型,它应该像?:但没有懒惰?
我的第一次尝试如下:
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 将它的参数转换为值类型。无论如何,重点是明确地表达类型,而不是通过auto 和typeof。
知道如何创建一个返回与?: 相同类型的函数吗?
【问题讨论】:
-
std::common_type,但这不会保留值类别,因为结果是std::decay'd。此外,C++11 的拼写是decltype,而不是typeof。 -
为什么不
decltype(b ? std::forward<T1>(true_result) : std::forward<T2>(false_result))? -
反正
?:的规则占标准的1.5页。它的某些部分需要知道 AFAIK 无法以编程方式确定的事情(例如,表达式是否可以转换为T&或T&&受引用必须直接绑定的约束);如果没有decltype(例如,通常的算术转换),其他方法也可以实现,但非常繁琐。 -
如果您需要 C++03 兼容性,您可能想查找这个:stackoverflow.com/a/2450157/34509。