开发者

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

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 ?


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)


You can probably use ostream_iterator instead:

vector<int> V;
// ...
copy(V.begin(), V.end(), ostream_iterator<int>(cout, "\n"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜