Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::bind and << operator in C++

Tags:

c++

bind

boost

I would like to bind the << stream operator:

for_each(begin, end, boost::bind(&operator<<, stream, _1));

Unfortunately it does not work:

Error   1   error C2780: 'boost::_bi::bind_t<_bi::dm_result<MT::* ,A1>::type,boost::_mfi::dm<M,T>,_bi::list_av_1<A1>::type> boost::bind(M T::* ,A1)' : expects 2 arguments - 3 provided c:\source\repository\repository\positions.cpp   90

What am I doing wrong ?

like image 569
0x26res Avatar asked May 07 '10 09:05

0x26res


People also ask

What is boost :: bind?

boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers, and is able to bind any argument to a specific value or route input arguments into arbitrary positions.

What does std :: bind do?

std::bind. The function template bind generates a forwarding call wrapper for f . Calling this wrapper is equivalent to invoking f with some of its arguments bound to args .

What is the use of bind in C++?

Bind function with the help of placeholders helps to manipulate the position and number of values to be used by the function and modifies the function according to the desired output.

What is _1 in boost :: bind?

_1 is a placeholder. Boost. Bind defines placeholders from _1 to _9 . These placeholders tell boost::bind() to return a function object that expects as many parameters as the placeholder with the greatest number.


2 Answers

Instead you might try boost.lambda:

//using namespace boost::lambda;
for_each(begin, end, stream << _1));

The reason of your problem is most probably: how on earth can you expect the compiler / bind to know what you are taking the address of if you say &operator<<? (I get a different error simply saying that this is not declared.)


If you really want to do it with bind, you'd have to tell it which operator<< you want to use, e.g assuming int (you'll also need to know, it the operator is overloaded as a member or free function):

bind(static_cast<std::ostream& (std::ostream::*)(int)>(&std::ostream::operator<<), ref(std::cout), _1)
like image 127
UncleBens Avatar answered Sep 26 '22 01:09

UncleBens


You can probably use ostream_iterator instead:

vector<int> V;
// ...
copy(V.begin(), V.end(), ostream_iterator<int>(cout, "\n"));
like image 26
Assaf Lavie Avatar answered Sep 24 '22 01:09

Assaf Lavie