#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);
}
编辑:
这
#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);
}
确实产生歧义。
顺便说一下,去掉const产生的歧义。
编译器:g++5.3.0 带有标志 --std=c++14
最佳答案
这不是一个错误。参数的类型是 const int*&
,它是对非常量的引用,不能绑定(bind)到不同类型的对象( int*
)。 (需要隐式转换,并且生成的临时文件不能绑定(bind)到非常量的引用。)
如果将参数的类型更改为对 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);
关于c++ - const T*& 和 const T* 不会在函数重载时产生歧义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40180724/