32

私は標準を読んでいて、キャストなしではこのコードが解決されない理由を理解しようとしています。

void foo(char c) { }

// Way bigger than char
void foo(unsigned long int) { }

int main()
{
   foo(123456789); // ambiguous
   foo((unsigned long int) 123456789); // works
}

これがそれが言うことです:

4.13 整数変換ランク [conv.rank]

すべての整数型には、次のように定義された整数変換ランクがあります。

— 符号なし整数型のランクは、対応する符号付き整数型のランクと等しくなければなりません。

— char のランクは、signed char および unsigned char のランクと等しくなければなりません。

特に、私のジミーをざわめかせるのは、符号なしの整数型ではなく、符号なしの char だけであるということです。私の推測では、変換によって char が unsigned 型に昇格されています。これは本当ですか?

4

1 に答える 1

52

It has little to do with rank of the type defined in 4.13. 4.13 defined internal rankings used to describe integral promotions and usual arithmetic conversions. They by itself do not directly affect overload resolution. Rankings relevant to overload resolution are defined in "13.3.3.1.1 Standard conversion sequences" and then used in "13.3.3.2 Ranking implicit conversion sequences".

So, it is about rank of the conversion as defined under 13.3. 123456789 is an integer literal of type int on your platform. This means that calling both char and unsigned long versions of your function requires an implicit conversion from int to char or from int to unsigned long. In both cases we have conversions of "integral conversion" type. That means that both functions are equally "bad" in this case. Hence the ambiguity.

If one of these functions required a mere integral promotion (as opposed to integral conversion), it would win the resolution and the call would be considered unambiguous. But alas both of your functions require integral conversions.

于 2014-09-24T07:32:19.083 に答える