Using boost function input iterator with class member functions

Hello, I am trying to use a class member function in conjunction with boost's function input iterator, and am having trouble coming up with a solution which can in any way be considered elegant... My initial thought process was to do something like : std::copy( // does not work because the functor (1st arg to make_function_input iterator ) cannot be temporary... or something like that boost::make_function_input_iterator(boost::bind(&My_Class::my_function, 0)), boost::make_function_input_iterator(boost::bind(&My_Class::my_function, 10)), std::ostream_iterator<result_type>(std::cout, " ") ); However, this fails as noted above. Thus, i had to look at some compiler error messages in order to figure out the return type of boost::bind and create some boost::bind object producing the working code below, however, this looks pretty terrible. Can anyone suggest a more convenient solution to the problem I am trying to solve? Thanks, Michael King #include<iostream> #include<iterator> #include<boost/bind.hpp> #include<boost/iterator/function_input_iterator.hpp> class foo { public: typedef double result_type; result_type return_random() const { return drand48(); } }; int main() { foo bar; // found type from compiler error message... boost::_bi::bind_t< double, boost::_mfi::cmf0< double, foo>, boost::_bi::list1< boost::_bi::value<foo> >
f = boost::bind(&foo::return_random, bar);
std::copy( boost::make_function_input_iterator(f, 1), boost::make_function_input_iterator(f, 10), std::ostream_iterator<double>(std::cout, "\n") ); return 0; }

Hi Michael, On Sun, Sep 4, 2011 at 8:29 PM, Michael King <wmichaelking1@gmail.com> wrote:
Can anyone suggest a more convenient solution to the problem I am trying to solve?
I was a little surprised that the function_input_iterator took its argument by reference -- it seems like such arguments are typically passed by value, allowing the client to use ref/cref. If you're able to use boost range, I think you can get a much more attractive syntax (example modified to work with g++ on windows). Using boost trunk: #include<cstdlib> #include<iostream> #include<iterator> #include<boost/bind.hpp> #include<boost/range/adaptor/transformed.hpp> #include<boost/range/algorithm/copy.hpp> #include<boost/range/irange.hpp> using boost::adaptors::transformed; class foo { public: typedef double result_type; result_type return_random() const { return std::rand() / (double)(RAND_MAX); } }; int main(int argc, char** argv) { foo bar; boost::copy( boost::irange(1,10) | transformed(boost::bind(&foo::return_random, bar)), std::ostream_iterator<double>(std::cout, "\n")); return 0; } HTH, Nate
participants (2)
-
Michael King
-
Nathan Crookston