#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:
This
#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);
}
Do produce ambiguity.
By the way, remove the const produce ambiguity.
compiler: g++5.3.0 with flag --std=c++14
- Why the following sample code do not produce ambiguity
This is not a bug. The parameter's type is const int*&
, it's a reference to non-const, which can't be bound to object with different type (int*
). (An implicit convertion is needed, and the produced temporary can't be bound to reference to non-const.)
If you change the parameter's type to reference to const:
void foo(const int* const&)
Or change the argument's type to const int*
:
const int* i=nullptr;
foo(i);
Both will trigger a compile error for ambiguous calling.
- Is there any way to call the second version? (If this is not a bug)
You can do it through a function pointer, explicitly specifying which one you want to pick up:
const int* i=nullptr;
static_cast<void(*)(const int*&)>(&foo)(i);