c++ - 函数参数绑定(bind)的完美转发和二义性

标签 c++ c++11

我正在试验 C++11 的完美转发功能。 Gnu g++ 编译器报告函数参数绑定(bind)的歧义问题(错误显示在下面的源代码之后)。我的问题是为什么会这样,因为遵循函数参数绑定(bind)过程我没有看到歧义。我的推理如下:在 main() 中调用 tf(a) 绑定(bind)到 tf(int&) 因为 a 是一个左值。然后函数 tf 将左值引用 int& a 转发给函数 g 因此函数 void g(int &a) 应该被唯一调用。因此,我看不出有歧义的原因。当从代码中删除重载函数 g(int a) 时,错误消失。这很奇怪,因为 g(int a) 不能成为与 int &a 绑定(bind)的候选对象。

这是我的代码:

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)

最佳答案

This is strange as g(int a) cannot be a candidate for binding with int &a.

那不是真的。如果您删除 g(int&) 重载,则 g(int) 将被调用。当两者都被声明时,它是不明确的,因为两者都是可行的候选者并且不需要转换。

关于c++ - 函数参数绑定(bind)的完美转发和二义性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18880571/

相关文章:

c++ - 如何将 char 字符串转换为 wchar_t 字符串?

c++ - CMAKE - 为库设置编译标志

algorithm - 在没有循环的情况下向向量的所有条目添加一个值

c++ - 对 Variadic 模板与 Visual Studio 2010 的混淆

c++ - Qt Creator错误无限循环

c++ - Visual Studio中的 "win32 project"名称与x86或x64平台有什么关系

c++ - 有效的 C++ 仍然有效吗?

c++ - C++模板参数中的常量表达式

c++ - C++ 数组可以在内存边界结束吗?

c++ - 成员变量包装器