ambigious functions in c++

孤人 提交于 2019-12-10 14:49:09

问题


I would like to know why these declarations won't work(are not compatible)

void f(int); //p1
void f(const int);//p2
void f(int &);//p3
void f(const int &);//p4

If I understood well, the compiler won't find a difference between (int &) and (const int &) and if I write f(12) it won't be able to choose between the two first declarations.. Am I right?


回答1:


p3 and p4 are perfectly unambiguous and distinguishable, p1 and p2 are not. (And of course p1/p2 are distinguishable from p3 and p4.)

The reason is that top-level const on a value parameter is not detectable and infact useless on a declaration. You can for example do the following:

void foo(int x); // declaration
// ...
void foo(const int x){
  // definition/implementation
}

The const here is an implementation detail that's not important for the caller, since you make a copy anyways. That copy is also the reason why it's not distinguishable from just int, from the callers side it's exactly the same.

Note that const int& r does not have a top-level const, it's the reference that refers to a constant integer (references are always constant). For pointers, which may be changed if not declared const, see also this question for where to put const.



来源:https://stackoverflow.com/questions/10122294/ambigious-functions-in-c

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