Greetings, I'm studying bind1st/bind2nd in STL and encountered the following question.
I have a vector<int> and I want to print all elems in that vector in sequence. Here's my buggy code.
1 2 3 4 5 6 7 8 9 10 11 12 13
void print(int value, ostream& os)
{ os << value << " "; }
int main()
{
vector<int> v;
... // initialize v, do not matter
for_each(v.begin(), v.end(), bind2nd(ptr_fun(print), cout)));
... // other code, do not matter
}
The compiler complains that "reference to reference is illegal". I found it's the reference type in print that triggers the failure. However, for ostream, it's always passing-by-reference idiom when used as parameter, isn't it. So how should I correct the code? Thank you.
Although std::copy and boost::bind + boost::ref provide better solutions to my needs, I still curious at how to make the code work in bind2nd case.
1 2
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); // use copy
for_each(v.begin(), v.end(), boost::bind(print, _1, boost::ref(cout))); // use boost