我可以在bind中使用流操作符吗?

Can I use stream operator with bind?

本文关键字:操作符 bind 我可以      更新时间:2023-10-16

我还在学习如何正确使用bind的c++11特性。下面是一个实验:

using namespace std::placeholders;
using namespace std;
struct MyType {};
ostream& operator<<(ostream &os, const MyType &n)
{
    os << n;
    return os;
}
int main()
{
    std::vector<MyType> vec;
    std::for_each(vec.begin(), vec.end(), std::bind(operator<<, std::ref(std::cout), _1));
    return 0;
}

我得到clang编译错误:

error: no matching function for call to 'bind'
    std::for_each(vec.begin(), vec.end(), std::bind(operator<<, std::ref(std::cout), _1));

我猜bind不能区分函数operator<<在我的文件中定义的那些预定义的。

但我想知道这是否真的可以做到,只是我做错了吗?

[编辑]谢谢ISARANDI,前缀::修复了这个问题。但是,如果在同一个命名空间我有重载函数:

using namespace std::placeholders;
using namespace std;
struct MyType {};
struct MyType2 {};
ostream& operator<<(ostream &os, const MyType &n)
{
    os << n;
    return os;
}
ostream& operator<<(ostream &os, const MyType2 &n)
{
    os << n;
    return os;
}
int main()
{
    std::vector<MyType> vec;
    std::for_each(vec.begin(), vec.end(), std::bind(::operator<<, std::ref(std::cout), _1));
    return 0;
}

在这种情况下,即使使用全局命名空间,我仍然会得到编译错误。这里有解决方案吗?

[EDIT2]好的,我明白了,我需要转换它:

std::for_each(vec.begin(), vec.end(), std::bind((ostream&(ostream&, const MyType&))::operator<<, std::ref(std::cout), _1));

由于using namespace std;, operator<<有多个过载。要显式选择您的版本,请写入

std::for_each(vec.begin(), vec.end(), std::bind(::operator<<, std::ref(std::cout), _1));

前缀by ::从全局命名空间中选择过载