我可以使用绑定的流操作符吗?

my_*_*ion 0 c++ c++11

我还在学习关于如何正确使用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;
}
Run Code Online (Sandbox Code Playgroud)

我得到了clang编译错误:

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

我猜绑定无法区分我的文件中定义的函数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;
}
Run Code Online (Sandbox Code Playgroud)

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

[编辑2]好的,想通了,我需要施展它:

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

isa*_*ndi 8

因为using namespace std; operator<<有多重载荷.为了明确选择你的版本,请写

std::for_each(vec.begin(), vec.end(), std::bind(::operator<<, std::ref(std::cout), _1));
Run Code Online (Sandbox Code Playgroud)

前缀通过::从全局命名空间中选择重载.