我想绑定<< stream运算符:
for_each(begin, end, boost::bind(&operator<<, stream, _1));
Run Code Online (Sandbox Code Playgroud)
不幸的是它不起作用:
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
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么 ?
相反,你可以试试boost.lambda:
//using namespace boost::lambda;
for_each(begin, end, stream << _1));
Run Code Online (Sandbox Code Playgroud)
你问题的原因很可能是:如果你说的话,你怎么能期望编译器/绑定知道你正在拿什么地址&operator<<
?(我得到一个不同的错误只是说没有声明.)
如果你真的想用bind做,你必须告诉它operator<<
你要使用哪个,例如假设int(你还需要知道,运算符作为成员或自由函数重载):
bind(static_cast<std::ostream& (std::ostream::*)(int)>(&std::ostream::operator<<), ref(std::cout), _1)
Run Code Online (Sandbox Code Playgroud)
您可以使用ostream_iterator代替:
vector<int> V;
// ...
copy(V.begin(), V.end(), ostream_iterator<int>(cout, "\n"));
Run Code Online (Sandbox Code Playgroud)