"modemer" <me@privacy.net.invalid> wrote:
If I define the following codes:
void f(const MyClass & in) {cout << "f(const)\n";}
void f(MyClass in) {cout<<"f()\n";}
MyClass myclass;
f(myclass);
Compiler complain that it can't find the best match. Anyone
could give a detail explanation in theory? Which one is good?
The same error also exists if myclass is declared const:
/////////////////////
void f(const MyClass & in) { cout << "f(const reference)\n"; }
void f(MyClass in) { cout << "f(value)\n"; }
const MyClass myclass;
f(myclass);
//
If "f(const reference)" is changed to "f(reference)", the error also
occurs!:
/////////////////////
void f(MyClass & in) { cout << "f(reference)\n"; }
void f(MyClass in) { cout << "f(value)\n"; }
MyClass myclass;
f(myclass);
//
However, the error does not occur -- and f(value) is called -- if myclass is
const:
/////////////////////
void f(MyClass & in) { cout << "f(reference)\n"; }
void f(MyClass in) { cout << "f(value)\n"; }
const MyClass myclass;
f(myclass);
//
The error will occur (twice) no-matter the constness of myclass if all three
functions are defined:
/////////////////////
void f(MyClass & in) { cout << "f(reference)\n"; }
void f(const MyClass & in) { cout << "f(const reference)\n"; }
void f(MyClass in) { cout << "f(value)\n"; }
const MyClass constmyclass;
MyClass myclass;
f(constmyclass);
f(myclass)
//
However, the compiler error doesn't exist if f(value) isn't defined:
/////////////////////
void f(MyClass & in) { cout << "f(reference)\n"; }
void f(const MyClass & in) { cout << "f(const reference)\n"; }
/*const*/ MyClass myclass;
f(myclass);
//
In the previous example though, when the program runs, f(reference) is
called if myclass is non-const and f(const reference) is called if myclass
is const.
The situations are exactly the same if "f(value)" is replaced with "f(const
value)". However, if both "f(value)" and "f(const value)" exist, the
compiler says that f(value) has already been defined (or "f(const value)",
depending on which is defined first).
Other responses in the thread indicate that it is possible to explicitly
specify which function to call. To me that seems like bending-over-backward
to deal with a possible shortcoming of the language and/or compiler.
Yes maybe the compiler should be able to handle the ambiguities better.
However, why differentiate functionality based only on switching the
non-const/const and/or value/reference nature of a function's parameter(s)?
(And if that is found to be useful, would it be called "ambiguous
polymorphishm"?)
crichmon