Boost logo

Boost :

From: Terje Slettebø (tslettebo_at_[hidden])
Date: 2004-10-10 09:37:23


>From: "Peter Dimov" <pdimov_at_[hidden]>

> David Abrahams wrote:
> > Terje Slettebø <tslettebo_at_[hidden]> writes:
> >
> >> // int_vector r_list = to_runtime<c_list>();
> >>
> >> int_vector r_list;
> >>
> >> boost::mpl::for_each<c_list>(to_sequence<int_vector>(r_list));
> >
> > Better yet:
> >
> > int_vector r_list;
> > boost::mpl::for_each<c_list>(std::back_inserter(r_list));
> >
> > Enjoy ;-)
>
> Um, how does this work? back_inserter returns an iterator, not a function
> object; is there some magic in mpl::for_each that I can't see? Maybe I'm
> looking at the wrong version?

Apparently not. However, you can always adapt one to the other, but I don't
know if that's an improvement:

template<class Iterator>
class iterator_to_functor_type
{
public:
  iterator_to_functor_type(const Iterator &i) : iterator(i) {}

  template<class Element>
  void operator()(Element e)
  {
    *iterator=e;

    ++iterator;
  }

private:
  Iterator iterator;
};

template<class Iterator>
iterator_to_functor_type<Iterator> iterator_to_functor(const Iterator &i)
{
  return iterator_to_functor_type<Iterator>(i);
}

boost::mpl::for_each<c_list>(iterator_to_functor(std::back_inserter(r_list))
);

The behaviour of mpl::for_each is consistent with std::for_each, as both
takes a function (object) where each element is passed to. However, thinking
more about this fusion of compile-time and run-time, how about having an MPL
copy function, that copies from a compile-time sequence, to a run-time
sequence (or vice versa)? With it, one could use all the arsenal of the
standard library using iterators, including iterator adapters for insertion
and streams:

template<class Sequence,class Iterator>
void copy(const Iterator &i)
{
  boost::mpl::for_each<Sequence>(iterator_to_functor(i));
}

This way, we get:

    copy<c_list>(std::back_inserter(r_list));

Simple and clear.

Output of a compile-time sequence is also trivial:

    copy<c_list>(std::ostream_iterator<int>(std::cout,","));

Could we have this, please? :)

Now, I know that we can't overload class templates (can we do something
about that?), so this has to be called something else than "copy", as
there's already one in MPL, or one might use partial specialisation to
enable them to coexist.

Regards,

Terje


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