使用重载函数定义编译 C++ 时,为什么有符号和无符号整数类型的提升行为不同?这是预期的行为吗?
在下面的示例中,main 中对“fail”的调用是模棱两可的,但对“pass”的调用不是。
unsigned int fail(unsigned int a) {
return a;
}
unsigned int fail(unsigned short a) {
return a;
}
int pass(int a) {
return a;
}
int pass(short a) {
return a;
}
int main(){
unsigned char a;
char b;
fail(a);
pass(b);
return 0;
}
示例输出(来自 clang,VS 编译器给出了类似的内容):
fail.cpp:22:3: error: call to 'fail' is ambiguous
fail(a);
^~~~
fail.cpp:1:14: note: candidate function
unsigned int fail(unsigned int a) {
^
fail.cpp:5:14: note: candidate function
unsigned int fail(unsigned short a) {
^
1 error generated.
最佳答案
根据integral promotion (强调我的):
The following implicit conversions are classified as integral promotions:
signed char
[...] can be converted toint
;unsigned char
[...] can be converted toint
if it can hold its entire value range, andunsigned int
otherwise;char
can be converted toint
orunsigned int
depending on the underlying type:signed char
orunsigned char
(see above);Note that all other conversions are not promotions; for example, overload resolution chooses
char
->int
(promotion) overchar
->short
(conversion).
在您的情况下,鉴于 int
能够同时保存 signed char
和 unsigned char
的整个值范围,只有 >int pass(int a)
是一种提升,比剩下的三个转化更可取,转化之间没有偏好。
关于C++ 重载与有符号和无符号 int 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49817416/