Can we overload a function based on only whether a parameter is a value or a reference?

时光怂恿深爱的人放手 提交于 2020-01-21 04:45:42

问题


I got the answer NO! Because passing by value and passing by reference looks identical to the caller.

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?


回答1:


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.

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.




回答2:


You can call each method:

void (A::*t)(int& ) =&A::f;
A a;
int i = 9;
int& j = i;   
a.f(1); //  f(int i)
(a.*t)(i); // f(int& i)


来源:https://stackoverflow.com/questions/2458090/can-we-overload-a-function-based-on-only-whether-a-parameter-is-a-value-or-a-ref

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!