【发布时间】:2017-03-12 21:26:22
【问题描述】:
我正在学习新的 C++ 语义,但这个程序出现错误:
#include <iostream>
#include <string>
#include <utility>
std::string foo(std::string str)
{
return str + " call from normal";
}
std::string foo(const std::string& str)
{
return str + " call from normal";
}
std::string foo(std::string&& str)
{
return str + " call from ref ref";
}
int main()
{
std::string str = "Hello World!";
std::string res = foo(str);
std::string&& res_ref = foo(std::move(str));
std::cout << "Res ref = " << res_ref << std::endl;
std::cout << "Str = " << str << std::endl;
return 0;
}
错误是:
:23:30: error: call of overloaded ‘foo(std::__cxx11::string&)’ is ambiguous std::string res = foo(str);
为什么调用不明确?
【问题讨论】:
-
你有 3 个
foo函数,它无法确定你要使用哪一个。 -
但是它的双重引用,标准函数和常量引用,为什么会出现这个问题?当我评论第一个函数声明时一切正常,我的问题是:为什么编译器不能选择一个用途?
-
编译器应该如何知道是调用
std::string foo(std::string str)还是std::string foo(const std::string& str)?您以完全相同的方式调用它们 -
好的...那么有没有办法强制编译器使用标准方法?
-
不,编译器无法区分这两个函数——而且我想不出这在任何情况下都有用。
标签: c++ c++14 overload-resolution