Const T * & and const T * do not create ambiguity when overloading a function

  • Why the following sample code is not ambiguous.
  • Is there a way to invoke the second version? (If this is not a mistake)

#include <iostream>
using namespace std;

void foo(const int*){cout << "no ref";}
void foo(const int*&){cout << "on ref";}

int main()
{
   int* i=nullptr;
   foo(i);
}

EDIT:

it

#include <iostream>
using namespace std;

void foo(const int){cout << "no ref";}
void foo(const int&){cout << "on ref";}

int main()
{
   int i=0;
   foo(i);
}

Generate ambiguity.


By the way, remove const due to ambiguity.

compiler: g ++ 5.3.0 with the flag --std = C ++ 14

+4
source share
1 answer
  • Why the following sample code is not ambiguous.

It's not a mistake. The parameter type const int*&is a reference to non-const, which cannot be bound to an object with a different type ( int*). (An implicit conversion is required, and the created temporary cannot be bound to a non-const reference.)

const:

void foo(const int* const&)

const int*:

const int* i=nullptr;
foo(i);

.

  • ? ( )

, , :

const int* i=nullptr;
static_cast<void(*)(const int*&)>(&foo)(i);
+4

Source: https://habr.com/ru/post/1658471/


All Articles