Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ambigious functions in c++

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?

like image 211
orangepixel Avatar asked Apr 12 '12 11:04

orangepixel


People also ask

What is ambiguous in C?

Access to a base class member is ambiguous if you use a name or qualified name that does not refer to a unique function or object. The declaration of a member with an ambiguous name in a derived class is not an error.

What is ambiguous function C++?

You cannot override one virtual function with two or more ambiguous virtual functions. This can happen in a derived class that inherits from two nonvirtual bases that are derived from a virtual base class.

How overloaded function is ambiguous?

In Function overloading, sometimes a situation can occur when the compiler is unable to choose between two correctly overloaded functions. This situation is said to be ambiguous. Ambiguous statements are error-generating statements and the programs containing ambiguity will not compile.

What is ambiguity error?

Ambiguity errors occur when erasure causes two seemingly distinct generic declarations to resolve to the same erased type, causing a conflict.


1 Answers

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.

like image 81
Xeo Avatar answered Oct 15 '22 15:10

Xeo