Perfect forwarding and ambiguity of function-parameter binding
I am experimenting with the perfect forwarding feature of C++11. Gnu g++
compiler reports an ambiguity issue of function-parameter binding (the
error is shown after the source code below). My question is why is it so,
as following the function-parameter binding process I don't see the
ambiguity. My reasoning is as follows: call to tf(a) in main() binds to
tf(int&) since a is an lvalue. Then function tf forwards the lvalue
reference int& a to function g hence the function void g(int &a) should be
uniquely invoked. Thus I do not see the reason for ambiguity. The error
disappears when the overloaded function g(int a) is removed from the code.
This is strange as g(int a) cannot be a candidate for binding with int &a.
Here is my code:
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;
}
Compilation g++ -std=c++11 perfectForwarding.cpp reports the following
errors:
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)
No comments:
Post a Comment