Rick wrote:
> Is the following appropriate behavior? It certainly isn't what I
> expected.
So your expectations are wrong. :-)
>
>
> #include <iostream>
>
> using namespace std;
>
> template<typename T> bool fun(const T& value) {
> cout << "In fun(const T&);" << endl;
>
> }
>
> template<typename T> bool fun(T value) {
> cout << "In fun(T);" << endl;
>
> }
>
> int main(int argc, char** argv) {
> fun(static_cast<const int&>(10) );
>
> }
>
> $ CC test.C
> "test.C", line 14: Error: Overloading ambiguity between
> "fun<int>(const int&)" and "fun<int>(int)".
> 1 Error(s) detected.
> $
> $
> $ g++ test.C
> test.C: In function `int main(int, char**)':
> test.C:14: error: call of overloaded `fun(const int&)' is ambiguous
> test.C:5: note: candidates are: bool fun(const T&) [with T = int]
> test.C:9: note: bool fun(T) [with T = int]
> $
>
> I would have said that if I tell the compiler explicitly that I
> want a const int&, there is no ambiguity. Something in the C++
> standard apparently says that this is correct behavior, but it
> seems wrong to me.
Your problem is that there is not such thing as "a const int&",
because that is just a reference to an object that exists elsewhere.
It can't exist by itself.
Try this instead, assuming a class Person:
Person Robert; // A person called Robert
Person& Bob = Robert; // Another name for Robert
fun(Robert);
fun(Bob);
Do you want different overloads called depending on what name we use
for the same person? No!
Now this:
const number ten = 10;
const number& also_ten = ten;
fun(ten);
fun(also_ten);
Do you want different overloads called depending on what name we use
for the number 10? Not really!
Bo Persson


|