tags:

views:

459

answers:

2

I'm trying to use Boost::bind and std::copy to print out the values in a list of lists. Obviously, I could use loops, and I may end up doing so for clarity, but I'd still like to know what I'm doing wrong here.

Here is the distilled version of my code:

#include <boost/bind.hpp>
#include <iterator>
#include <algorithm>
#include <list>
#include <iostream>
using namespace std;
using namespace boost;

int main(int argc, char **argv){
list<int> a;
a.push_back(1);

list< list<int> > a_list;
a_list.push_back(a);

ostream_iterator<int> int_output(cout,"\n");

for_each(a_list.begin(),a_list.end(),
  bind(copy,
    bind<list<int>::iterator>(&list<int>::begin,_1),
    bind<list<int>::iterator>(&list<int>::end,_1),
    ref(int_output)
  ) //compiler error at this line
);
return 0;

}

The compiler error starts off

error: no matching function call to bind(<unresolved overloaded function type> .....

I think this means that bind can't figure out what the return type for the outermost bind should be. I don't blame it, because I can't either. Any ideas?

+5  A: 

The template arguments to std::copy cannot deduced in the context of the bind call. You need to specify them explicitly:

copy< list<int>::iterator, ostream_iterator<int> >

Also when you write:

for_each(a_list.begin().a_list.end(),

I think that you mean:

for_each(a_list.begin(),a_list.end(),

And you're missing #include <iostream> for definition of std::cout.

Charles Bailey
I fixed the iostream and ., errors.
Dan Hook
Works perfectly. Thanks!
Dan Hook
+3  A: 

A way to solve this problem that may generate clearer code is to forget about Boost::bind altogether and define a functor:

struct print_int_list : public unary_function<list<int>, void>
{
   void operator()(list<int> b)
   { 
     copy(b.begin(),b.end(),ostream_iterator<int>(cout,"\n"));
   }
};

and just do

for_each(a_list.begin(),a_list.end(),print_int_list());

Boost::bind is great but sometimes I have to resist the urge to use it in places where simpler alternatives generate clearer code.

Dan Hook
+1 for your last paragraph. You can serious hurt readability by over-using boost::bind and friends.
Charles Bailey