自动提升算术运算

Automatic promotion of arithmetic operations

请看下面代码:

#include <type_traits>
int main()
{
    using T = short;
    auto x = T(1) + T(1);
    static_assert(std::is_same_v<decltype(x), T>);
}

上面的 static_assert 似乎对所有 gcc、clang 和 msvc 都失败了,我不明白为什么。如果我将 short 更改为 boolcharsigned charunsigned charunsigned short 中的任何一个,断言仍然会失败,因为对于所有这些情况 decltype(x) 被推断为 int.

根据 https://en.cppreference.com/w/cpp/language/operator_arithmetic 中的解释,这是正确的行为吗?

是的,需要从 short 升级到 int

来自https://en.cppreference.com/w/cpp/language/operator_arithmetic

If the operand passed to an arithmetic operator is integral or unscoped enumeration type, then before any other action (but after lvalue-to-rvalue conversion, if applicable), the operand undergoes integral promotion.

来自 https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion(强调我的):

prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int). In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.

最后:

signed char or signed short can be converted to int;