【发布时间】:2023-01-31 14:45:31
【问题描述】:
我试图编写一个重载函数来接受有符号和无符号整数。
以下是我的代码:
#include <iostream>
void fun(const long long a)
{
std::cout << "Signed: " << a << std::endl;
}
void fun(const unsigned long long a)
{
std::cout << "unsigned: " << a << std::endl;
}
int main()
{
unsigned int v = 10;
fun(v);
return 0;
}
这给出了以下编译错误。
main.cpp:17:5: error: call to 'fun' is ambiguous
fun(v);
^~~
main.cpp:4:6: note: candidate function
void fun(const long long a)
^
main.cpp:9:6: note: candidate function
void fun(const unsigned long long a)
^
1 error generated.
我假设它会工作得很好,因为 unsigned int 可以用 unsigned long long 类型表示。
谁能帮我理解这个错误?
【问题讨论】:
-
从 C++20 开始,重载的替代方法是一对带有
requires子句的模板函数,以指定一个函数只考虑有符号整数,另一个函数只考虑无符号整数,
标签: c++ overloading integer-promotion