C ++函数重载解析,涉及值传递,引用和常量引用 [英] C++ function overloading resolution involving pass-by-value, reference and constant reference

查看:51
本文介绍了C ++函数重载解析,涉及值传递,引用和常量引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我用C ++中的以下3个签名定义了一些函数 f :

Suppose I define some function f with the following 3 signatures in C++:

void f(int x) {}
void f(int& x) {}
void f(const int& x) {}

这些函数可以共存,因为它们的参数类型不同.

These functions can coexist since they differ in the types of the arguments.

现在,我运行以下代码:

Now I run the following code:

int main {
   int i = 3;
   const int ci = 4;

   f(3);
   f(i);
   f(ci);
}

在这种特定情况下,C ++如何知道要调用哪个重载函数?为了避免歧义,在C ++中编写重载函数的一般规则是什么(最佳实践?).当前的C ++ 14标准是否指定任何特定规则?

How does C++ know which overloaded function to call in this specific case ? What are rules in general ( best practice ? ) for writing overloaded functions in C++ as to avoid ambiguity. Does the current C++14 standard specify any specific rules ?

推荐答案

这三个调用都是模棱两可的,因此程序将无法编译.

All three calls are ambiguous, so the program won't compile.

f(3);

这可以使用第一个或第三个重载.它们同样好,因此通话很含糊.

This could use either the first or third overload. They are equally good, so the call is ambiguous.

f(i);

这可以使用第一次,第二次或第三次重载.第二个比第三个好;第二个比第三个好.在可能的情况下,绑定到 int& 优于绑定到 const int& .因此,以这种方式重载cv-qualification很好.但是第一次和第二次重载之间存在歧义.

This could use the first, second, or third overload. The second is better than the third; binding to int& is preferred over binding to const int& when it's possible. So it's fine to overload on cv-qualification in this way. But there is an ambiguity between the first and second overloads.

f(ci);

这可以使用第一个或第三个重载.同样,它们同样出色,因此通话不明确.

This could use the first or third overload. Again, they are equally good, so the call is ambiguous.

该标准精确规定了过载解决的规则.它们非常复杂,因此以某种方式使函数重载以致使读者难以分辨将调用哪个重载是一个不好的主意.您可以在此处找到规则.

The standard precisely specifies the rules of overload resolution. They are very complicated, so it is a bad idea to overload functions in a way that makes it hard for the reader to tell which overload will be called. You can find the rules here.

这篇关于C ++函数重载解析,涉及值传递,引用和常量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆