Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

c++ - Can I use stream operator with bind?

I am still learning c++11 features around how to use bind properly. Here is an experiment:

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;
}

I get clang compile error:

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

I guess bind cannot distinguish the function operator<< defined in my file from those pre-defined.

But I wonder if it actually can be done and just I did it wrong?

[EDIT] Thanks ISARANDI, prefixing :: fixed the problem. But how about at the same namespace I have overloaded functions:

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;
}

In this case, I still get that compile error even with the global namespace.. Is there a solution here?

[EDIT2]OK, figured out, I need to cast it:

std::for_each(vec.begin(), vec.end(), std::bind((ostream&(ostream&, const MyType&))::operator<<, std::ref(std::cout), _1));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because of using namespace std; operator<< has multiple overloads. In order to explicitly select your version, write

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

Prefixing by :: selects the overload from the global namespace.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...