Why does the most negative int value cause an error about ambiguous function overloads?

后端 未结 3 516
眼角桃花
眼角桃花 2020-11-28 08:10

I\'m learning about function overloading in C++ and came across this:

void display(int a)
{
    cout << \"int\" << endl;
}

void display(unsigned         


        
3条回答
  •  孤独总比滥情好
    2020-11-28 09:02

    This is a very subtle error. What you are seeing is a consequence of there being no negative integer literals in C++. If we look at [lex.icon] we get that a integer-literal,

    integer-literal
            decimal-literal integer-suffixopt
            [...]

    can be a decimal-literal,

    decimal-literal:
            nonzero-digit
            decimal-literal ’ opt digit

    where digit is [0-9] and nonzero-digit is [1-9] and the suffix par can be one of u, U, l, L, ll, or LL. Nowhere in here does it include - as being part of the decimal literal.

    In §2.13.2, we also have:

    An integer literal is a sequence of digits that has no period or exponent part, with optional separating single quotes that are ignored when determining its value. An integer literal may have a prefix that specifies its base and a suffix that specifies its type. The lexically first digit of the sequence of digits is the most significant. A decimal integer literal (base ten) begins with a digit other than 0 and consists of a sequence of decimal digits.

    (emphasis mine)

    Which means the - in -2147483648 is the unary operator -. That means -2147483648 is actually treated as -1 * (2147483648). Since 2147483648 is one too many for your int it is promoted to a long int and the ambiguity comes from that not matching.

    If you want to get the minimum or maximum value for a type in a portable manner you can use:

    std::numeric_limits::min();  // or max()
    

提交回复
热议问题