【发布时间】:2013-09-18 19:20:37
【问题描述】:
我正在试验 C++11 的完美转发功能。 Gnu g++ 编译器报告函数参数绑定的歧义问题(错误显示在下面的源代码之后)。我的问题是为什么会这样,按照函数参数绑定过程,我没有看到歧义。我的推理如下:在 main() 中调用 tf(a) 绑定到 tf(int&) 因为 a 是一个左值。然后函数 tf 将左值引用 int& a 转发给函数 g 因此函数 void g(int &a) 应该被唯一地调用。因此,我看不出模棱两可的原因。当从代码中删除重载函数 g(int a) 时,错误消失。这很奇怪,因为 g(int a) 不能成为与 int &a 绑定的候选对象。
这是我的代码:
void g(int &&a)
{
a+=30;
}
void g(int &a)
{
a+=10;
}
void g(int a) //existence of this function originates the ambiguity issue
{
a+=20;
}
template<typename T>
void tf(T&& a)
{
g(forward<T>(a));;
}
int main()
{
int a=5;
tf(a);
cout<<a<<endl;
}
编译g++ -std=c++11 perfectForwarding.cpp报告以下错误:
perfectForwarding.cpp: In instantiation of ‘void tf(T&&) [with T = int&]’:
perfectForwarding.cpp:35:7: required from here
perfectForwarding.cpp:24:3: error: call of overloaded ‘g(int&)’ is ambiguous
perfectForwarding.cpp:24:3: note: candidates are:
perfectForwarding.cpp:6:6: note: void g(int&&) <near match>
perfectForwarding.cpp:6:6: note: no known conversion for argument 1 from ‘int’ to ‘int&&’
perfectForwarding.cpp:11:6: note: void g(int&)
perfectForwarding.cpp:16:6: note: void g(int)
【问题讨论】: