有全局函数(只是例子):
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
可以同时转换为 char
和 int
,因此会产生歧义。
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/