c++ - 删除重载函数。 C++11。重载的调用......是模棱两可的

标签 c++ c++11

有全局函数(只是例子):

void func( int i )
{
    std::cout << i + 100 << std::endl;
}

我假设用 char 参数调用这个函数没有任何意义,所以我使用 delete:

void func(char) = delete;

所以我希望可以进行以下调用:

func(1);
func(3.1);
func(true);

并且应该禁止使用 char 参数调用:

func('a');

但事实并非如此。当调用 func('a') 时,我得到了预期的结果:

error: use of deleted function ‘void func(char)’

但是在调用 func(2.3) 期间我得到:

error: call of overloaded ‘func(double)’ is ambiguous

为什么会出现此错误?没有删除带有 char 参数的函数 double 被转换为 int 并调用了 func(int),为什么现在它被禁止了?

最佳答案

当你打电话时

func(2.3)

您将 double 传递给函数。候选列表包含两者 func(int)func(char),因为发生重载解析before delete kicks in :

If the function is overloaded, overload resolution takes place first, and the program is only ill-formed if the deleted function was selected Ref: cppreference.com, see Avishai's answer for precise standard quotes.

现在 double 可以同时转换为 charint,因此会产生歧义。

Without deleting function with char arguments double was converted to int and func(int) was called, why now it is forbidden?

即使没有delete char 版本,您也会收到歧义错误,请查看实时 here .当然,如果您只定义了 func(int),那么就不会出现歧义,因此 double 将很乐意转换为 int

关于c++ - 删除重载函数。 C++11。重载的调用......是模棱两可的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48011854/

相关文章:

c++ - 当我们迭代它时更改 HashMap 的行为是否已定义?

c++ - 是否有与 BUCK 的 header_namespace 等效的 cmake?

c++ - 如何在 C++ 中自动刷新日志消息并解锁互斥量?

c++ - 在 std::for_each 中返回 std::move(f)

c++ - 什么时候对流类型使用 std::swap?

java - 与 Java 相比,C++ move 语义性能

c++ - 我应该在 `#include` 中添加 `main(){}` 语句吗?

c++ - 将整数读入不同的 vector

c++ - 如何在不更改命令行的情况下禁用断言?

c++ - 进程被第三方应用程序 (Sprint Smartview) 杀死