Boost logo

Boost :

Subject: Re: [boost] [Bind] How do I get bind to deduce the return type of for_each?
From: Roland Bock (rbock_at_[hidden])
Date: 2010-04-15 17:50:08


Thomas Jordan wrote:
> Hi,
> I have been trying to use Boost.bind to create an 'STL algorithm function object' to pass into another, 'higher order,' STL algorithm (e.g., to pass a for_each into a for_each). However, I am struggling to get bind to deduce the correct return type of the for_each function object. I include the relevant bits of the code below.
>
> class myClass
> {
> public:
> int func(){return mValue;}
> private:
> int mValue;
> };
>
> //wrapper for STL for_each
> struct myForEach
> {
> template <typename II, typename F>
> F operator()(II begin, II end, F function) const
> {
> return std::for_each(begin, end, function);
> }
> };
>
> typedef vector<myClass> vocType;
> typedef vector<vocType> vovType;
>
> //overloaded member functions vocType::begin & end
> typedef vocType::iterator (vocType::*fnPtr)();
> typedef const vocType::iterator (vocType::*constFnPtr)() const;
>
> vovType vov(10, vocType(10, myClass()));
>
> main()
> {
> for_each(vov.begin(), vov.end(),
> bind< ? >(myForEach(),
> bind(static_cast<fnPtr>(&vocType::begin),_1),
> bind(static_cast<fnPtr>(&vocType::end),_1),
> protect(bind(&myClass::func, _1)))
> }
>
> I tried various things for bind<?>, but was only able to get the code to compile (eventually) on my Unix box when I substituted
> bind< boost::_bi::protected_bind_t<boost::_bi::bind_t<int, boost::_mfi::mf0<int, myClass>, boost::_bi::list1<boost::arg<1> (*)()> > > > for
> the bind<?>. I had guessed this might work from studying the compiler error messages. Obviously, this is not an ideal solution!
>
> Also, I only used the myForEach wrapper after having first attempted - and similarly failed - to bind the raw STL for_each.
>
> Is there any way I can help bind to deduce the correct return type - for either myForEach or std::for_each, or both?
>
>
>
In my experience it is easier to use a named functor object. Such as

function<void (const vocType&)> functor = bind(&myClass::func, _1);
std::for_each(vov.begin(), vov.end(), functor);

Untested, but I am pretty sure something along these lines will work.

Regards,

Roland


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk