C++11 中 "auto var = {condition} ? 1 : 1.0" 的类型是什么?它是双精度还是整数?
What is the type of "auto var = {condition} ? 1 : 1.0" in C++11? Is it double or int?
在 C++11 中,当我写这个时 x
和 y
的类型是什么?
int main()
{
auto x = true ? 1 : 1.0;
auto y = false ? 1 : 1.0;
std::cout << x << endl;
std::cout << y << endl;
return 0;
}
类型将为 double
,因为它是文字 1
和 1.0
.
的 common type
有一种简单的方法可以使用 typeid
进行测试:
#include <iostream>
#include <typeinfo>
using namespace std;
int main() {
auto x = true ? 1 : 1.0;
cout << typeid(x).name() << endl;
return 0;
}
这会在我的 GCC 版本上输出 d
。
运行 echo d | c++filt -t
然后告诉我们 d
对应于类型 double
,正如预期的那样。
根据C++标准中条件运算符的描述(5.16条件运算符)
6 Lvalue-to-rvalue (4.1), array-to-pointer (4.2), and
function-to-pointer (4.3) standard conversions are performed on the
second and third operands. After those conversions, one of the
following shall hold:
— The second and third operands have arithmetic or enumeration type;
the usual arithmetic conversions are performed to bring them to a common type, and the result is of that type.
和(5 个表达式)
10 Many binary operators that expect operands of arithmetic or
enumeration type cause conversions and yield result types in a similar
way. The purpose is to yield a common type, which is also the type of
the result. This pattern is called the usual arithmetic conversions,
which are defined as follows:
— Otherwise, if either operand is double, the other shall be converted
to double.
在条件运算符的两种用法中,其中一个操作数是具有双精度类型的浮动文字 - 1.0
(C++ 标准:浮动文字的类型是 double 除非由后缀明确指定。)
auto x = true ? 1 : 1.0;
auto y = false ? 1 : 1.0;
因此另一个操作数也将转换为双精度类型,并且表达式的结果具有双精度类型。
在 C++11 中,当我写这个时 x
和 y
的类型是什么?
int main()
{
auto x = true ? 1 : 1.0;
auto y = false ? 1 : 1.0;
std::cout << x << endl;
std::cout << y << endl;
return 0;
}
类型将为 double
,因为它是文字 1
和 1.0
.
有一种简单的方法可以使用 typeid
进行测试:
#include <iostream>
#include <typeinfo>
using namespace std;
int main() {
auto x = true ? 1 : 1.0;
cout << typeid(x).name() << endl;
return 0;
}
这会在我的 GCC 版本上输出 d
。
运行 echo d | c++filt -t
然后告诉我们 d
对应于类型 double
,正如预期的那样。
根据C++标准中条件运算符的描述(5.16条件运算符)
6 Lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are performed on the second and third operands. After those conversions, one of the following shall hold:
— The second and third operands have arithmetic or enumeration type; the usual arithmetic conversions are performed to bring them to a common type, and the result is of that type.
和(5 个表达式)
10 Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:
— Otherwise, if either operand is double, the other shall be converted to double.
在条件运算符的两种用法中,其中一个操作数是具有双精度类型的浮动文字 - 1.0
(C++ 标准:浮动文字的类型是 double 除非由后缀明确指定。)
auto x = true ? 1 : 1.0;
auto y = false ? 1 : 1.0;
因此另一个操作数也将转换为双精度类型,并且表达式的结果具有双精度类型。