gpt4 book ai didi

c++ - common_type 的可疑定义

转载 作者:太空狗 更新时间:2023-10-29 21:03:30 40 4
gpt4 key购买 nike

在 Nicolai M. Josuttis 的“The Cpp standard library”一书中,第 2 版中说(5.4,p.125)struct common 类型的定义如下:

template <typename T1, typename T2>
struct common_type<T1,T2> {
typedef decltype(true ? declval<T1>() : declval<T2>()) type;
};

我很难相信这是 common_type 的正确定义。原因:

typedef decltype(true ? declval<T1>() : declval<T2>()) type;//As far as I understand this will always pick second operand, declval<T1>(), due to the fact that there is 'true' value. Am I right?

最佳答案

都是关于条件运算符的。 它不是选择语句,如 if 或 switch。

ISO C++11标准5.16段:

Otherwise, if the second and third operand have different types and either has (possibly cv-qualified) class type, or if both are glvalues of the same value category and the same type except for cv-qualification, an attempt is made to convert each of those operands to the type of the other.

因此,decltype 包含 true 条件并不重要,编译器必须选择普通类型作为结果。

UPD: 5.16 包含对正确行为的进一步描述,您应该查看它以完全理解整个过程。但是对于您的特定问题:

Using this process, it is determined whether the second operand can be converted to match the third operand, and whether the third operand can be converted to match the second operand. If both can be converted, or one can be converted but the conversion is ambiguous, the program is ill-formed. If neither can be converted, the operands are left unchanged and further checking is performed as described below. If exactly one conversion is possible, that conversion is applied to the chosen operand and the converted operand is used in place of the original operand for the remainder of this section.

关于c++ - common_type 的可疑定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13269792/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com