Boost logo

Boost Users :

Subject: Re: [Boost-users] Copy MPL sequence at runtime?
From: Rhys Ulerich (rhys.ulerich_at_[hidden])
Date: 2010-03-18 11:16:56


>>> I'd like to copy the contents of a boost::mpl::vector_c (or similar)
>>> into an output iterator at runtime.

Thank you for the help Rutger, Kim, and Steven, and especially for the
mpl::for_each examples and the copy functor.

The more complete use case was to turn an MPL sequence into a form
usable within an initialization list for either boost::array or
something requiring an iterator. For completeness, the helper class I
finally went with is below.

I appreciate your expertise,
Rhys

#define BOOST_TEST_MODULE $Id: test_mpl.cc 999 2010-03-18 15:08:46Z rhys $
#include <boost/array.hpp>
#include <boost/mpl/vector_c.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/size.hpp>
#include <boost/test/included/unit_test.hpp>

template< typename Sequence >
class sequence_array
    : public boost::array<
            typename Sequence::value_type,
            boost::mpl::size<Sequence>::type::value
>
{
    typedef typename boost::array<
                typename Sequence::value_type,
                boost::mpl::size<Sequence>::type::value
>::iterator iterator;

    struct copier_ {
        copier_(iterator it) : it_(it) {}
        template<typename U> void operator()(U u) { *(it_++) = u; }
        iterator it_;
    };

public:
    sequence_array() {
        boost::mpl::for_each<Sequence>(copier_(this->begin()));
    }
};

BOOST_AUTO_TEST_CASE( testing )
{
    sequence_array< boost::mpl::vector_c<int,2,4,6> > a;

    BOOST_CHECK_EQUAL(a[0], 2);
    BOOST_CHECK_EQUAL(a[1], 4);
    BOOST_CHECK_EQUAL(a[2], 6);

    boost::array<int, 3> b = { 2, 4, 6 };

    BOOST_CHECK( b == a );
    BOOST_CHECK( a == b );

}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net