【问题标题】:Not able to compile code with unsigned and signed overloads of a function [duplicate]无法使用函数的无符号和有符号重载编译代码[重复]
【发布时间】: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


【解决方案1】:

通常,无符号整数可以隐式转换为更大的(无)符号整数,而不会丢失任何数据。在大多数实现中,(un)signed long long 大于 unsigned int

由于unsigned int 可隐式转换为long longunsigned long long,因此编译器不知道您要调用哪个重载,因此会出现错误。因此,您必须明确告诉它要使用哪个重载,例如:

fun(static_cast<unsigned long long>(v));

或者

static_cast<void (*)(const unsigned long long)>(fun)(v);

或者

void (*f)(const unsigned long long) = fun;
f(v);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 2013-10-28
    • 1970-01-01
    相关资源
    最近更新 更多