Search code examples
c++integer-promotion

C++ negation and overload resolution


In Microsoft Visual Studio 2015, the following code:

void foo(int8_t a);
void foo(int16_t a);
void foo(int16_t a, int16_t b);

void f()
{
    int8_t x /* = some value */;
    foo(-int16_t(x)); // ERROR
}

Gives the following message:

foo

Error: more than one instance of overloaded function "function" matches the argument list:
    function "foo(int8_t a)"
    function "foo(int16_t a)"
    argument types are: (int)

What is going on here? Shouldn't it say "argument types are: (int16_t)"? Does this have something to with promotion? if so how can I turn promotion off?


Solution

  • Negate before you cast. Negating promotes to a machine size integer, hence the ambiguity.

    foo(int16_t(-x));