【发布时间】:2020-01-17 21:30:20
【问题描述】:
我知道我不应该重载一个函数,因为参数只有一个通过复制传递,另一个通过引用传递:
void foo(int x)
{
cout << "in foo(int x) x: " << x << endl;
}
void foo(int& x)
{
cout << "in foo(int& x) x: " << x << endl;
}
int main()
{
int a = 1;
foo(5); // ok as long as there is one best match foo(int)
foo(a); // error: two best candidates so the call is ambiguous
//foo(std::move(a));
//foo(std::ref(an)); // why also this doesn't work?
}
所以使用std::bind 的代码可以是这样的:
std::ostream& printVec(std::ostream& out, const std::vector<int> v)
{
for (auto i : v)
out << i << ", ";
return out;
}
int main()
{
//auto func = std::bind(std::cout, std::placeholders::_1); // error: stream objects cannot be passed by value
auto func = std::bind(std::ref(std::cout), std::placeholders::_1); // ok.
}
所以std::ref 在这里确保通过引用而不是通过值来避免歧义?
* 对我很重要的事情:std::bind() 是否实现了一些包装器来解决这个问题?
- 为什么我不能在我的示例中使用
std::ref来帮助编译器进行函数匹配?
【问题讨论】:
-
我在您的问题中没有看到任何包含
std::bind的代码。请澄清你在说什么。我怀疑你完全误解了 std bind 和 std ref 如何交互,但我不知道你是如何误解它的。因此,请提供一个 std bind 和 std ref 以您认为的方式交互(和重载)的示例。 -
std::ref返回std::reference_wrapper所以仍然需要转换。 en.cppreference.com/w/cpp/utility/functional/ref -
@Yakk-AdamNevraumont:已编辑。
标签: c++ function overloading stdbind