我们可以基于一个参数是一个值还是一个引用来重载一个函数? [英] Can we overload a function based on only whether a parameter is a value or a reference?

查看:137
本文介绍了我们可以基于一个参数是一个值还是一个引用来重载一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到答案不!

但是,下面的代码编译正确

However, the code below compiles right

class A {

public:
void f(int i) {}    

void f(int& i) {}
};

但是当我尝试使用它时,会出现编译错误。

But when I try to use it, there is compile error.

int main () {

   A a;
   int i = 9;
   int& j = i;
   a.f(1);
   a.f(i);
   a.f(j);
  return 0;
}

为什么编译器禁用它,即使不知道它将被使用?

Why does not the compiler disable it even without knowing it is going to be used?

推荐答案

是的,他们可以根据参考是否重载。这就是为什么要让他们这样共存是完全正确的;他们是不同的。

Yes, they can be overloaded based on reference or not. That is why it's perfectly fine to have them coexist like that; they are different.

问题与歧义有关。 f(1)只能在一个变体上调用, f(i)两者都不可取,因此你得到歧义的错误。如果您添加了第三个函数, foo(const int&)所有调用将是不明确的。但是所有的都是彼此的重载,并且没有冲突。

The problem has to do with ambiguity. While f(1) can only be called on one variation, f(i) can be called on both. Neither is preferable, therefore you get an error for ambiguity. If you added a third function, foo (const int&), all calls would be ambiguous. But all are still overloads of each other, and non-conflicting.

我同意能够有一个函数的三个重载是奇怪的,并且能够直接调用没有。也许别人有更多要添加。

I agree it's strange to be able to have three overloads of a function, and be able to directly call none. Perhaps someone else has more to add.

这篇关于我们可以基于一个参数是一个值还是一个引用来重载一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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