为什么int加上uint会返回uint?

Vah*_*agn 9 c++ int unsigned integer-arithmetic

int plus 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;
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 14

如果"应该是",则表示"我的编译器是否符合标准":是的.

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

许多期望算术或枚举类型的操作数的二元运算符会以类似的方式引起转换并产生结果类型.目的是产生一个通用类型,它也是结果的类型.此模式称为通常的算术转换,其定义如下:

  • 胡说
  • 否则,等等,
  • 其他,等等 ......
  • 否则,如果任一操作数是无符号的,则另一个操作数应转换为无符号.

如果"应该是",那么你的意思是"如果没有这个世界会变得更好":我没有能力回答这个问题.