以下函数应该像 ?: 一样工作,但没有惰性。你会将返回类型指定为什么?
我的第一次尝试如下:
template <typename T1, typename T2>
T1 myif(bool b, T1&& true_result, T2&& false_result)
{
if (b) {
return true_result;
} else {
return false_result;
}
}
但后来我发现了一个名为 "given" 的东西:
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
处理。另外,在 C++11 中正确的拼写是decltype
,而不是typeof
。 - T.C.decltype(b ? std::forward<T1>(true_result) : std::forward<T2>(false_result))
? - Casey?:
的规则占据了标准的1.5页。其中的一些部分需要知道 AFAIK 不可能通过编程确定的东西(例如,一个表达式是否可以转换为T&
或T &&
受到引用必须直接绑定的限制);而其他部分虽然可能实现,但是没有decltype
非常繁琐(例如,通常的算术转换)。 - T.C.