gpt4 book ai didi

c++ - 为什么 int 加上 uint 返回 uint?

转载 作者:可可西里 更新时间:2023-11-01 16:33:17 30 4
gpt4 key购买 nike

int 加上 unsigned int 返回一个 unsigned int。应该这样吗?

考虑这段代码:

#include <boost/static_assert.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/type_traits/is_same.hpp>

class test
{
static const int si = 0;
static const unsigned int ui = 0;

typedef BOOST_TYPEOF(si + ui) type;
BOOST_STATIC_ASSERT( ( boost::is_same<type, int>::value ) ); // fails
};


int main()
{
return 0;
}

最佳答案

如果“应该”是指“我的编译器的行为是否符合标准”:

C++2003:第 5 条第 9 段:

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:

  • blah
  • Otherwise, blah,
  • Otherise, blah, ...
  • Otherwise, if either operand is unsigned, the other shall be converted to unsigned.

如果“应该”是指“如果不这样做,世界会变得更好吗”:我没有资格回答这个问题。

关于c++ - 为什么 int 加上 uint 返回 uint?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10047614/

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