我正在尝试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;
}
Run Code Online (Sandbox Code Playgroud)
编译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)
Run Code Online (Sandbox Code Playgroud)
这很奇怪,因为g(int a)不能成为用int和a绑定的候选者.
这不是真的.如果你删除了g(int&)过载,那么g(int)就会被调用.当两者都被宣布时它是模棱两可的,因为两者都是可行的候选者并且不需要转换.
| 归档时间: |
|
| 查看次数: |
438 次 |
| 最近记录: |