Parametric Polymorphism and References

I get the feeling that this is a bad idea in C++, but before I abandon trying to make it work and go back to pointers and dereferencing (which work just fine) I though I'd ask. The idea here is to have an overloaded function taking references to various types, and here's a demonstration of it not working:

------------------------
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

void gimmi(int &x)
 {
     x = 42;
 }
void gimmi(int x)
 {
     std::cout << x;
 }
 
int main()
{
    int i=123;
    int &j = i;
    
    gimmi(j);           // Fails - ambiguous
    gimmi((int &)j);    // Fails - ambiguous
    gimmi((int &)i);    // Fails - ambiguous
    gimmi(i);           // Fails - ambiguous

    gimmi((int)i);      // Okay, except on Microsoft(?!?)
    gimmi(456);         // Okay

    return 0;
}

------------------------

Basically, once you've defined gimmi(int &x) *and* gimmi(int x) you have to cast to get it to disambiguate; but nothing I've tried allows me to cast to match gimmi(int &x). All attempts are still considered by the compilers as ambiguous. (I've tested this on gcc 10.2, gcc 5.9.4, clang 10.0.1, MSVC 19.28, ICC 18)

Any ideas what's going on? I don't need a solution - pointers work - but I'd like to know if this can be made to as well, or am I flogging a dead horse?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
void gimmi( int& ) { std::cout << "gimmi( lvalue reference to int )\n" ; }
void gimmi( const int& ) { std::cout << "gimmi( lvalue reference to const int )\n" ; }
void gimmi( int&& ) { std::cout << "gimmi( rvalue reference to int )\n" ; }

int main()
{
    int i = 23 ;
    const int j = 44 ;

    gimmi(i) ; // gimmi( lvalue reference to int )
    gimmi(j) ; // gimmi( lvalue reference to const int )
    gimmi(+i) ; // gimmi( rvalue reference to int )
}
Perfect, thanks! Other replies I've had elsewhere were along the lines of "but why do you want to do it". Do you, perchance, have chapter and verse on it?
> Do you, perchance, have chapter and verse on it?

The gory details are here:
Draft Standard: https://eel.is/c++draft/over
cppreference: https://en.cppreference.com/w/cpp/language/overload_resolution

The writeup on this page, specific to this particular question, may be easier to digest:
http://thbecker.net/articles/rvalue_references/section_03.html
Topic archived. No new replies allowed.