MPL: flatten implementation not working
Hi all, I came up with the following implementation of a "flatten" operation that turns a sequence of sequences into a flat list: 8< ------------------------------------------------------------------- #include <iostream> #include <boost/mpl/vector.hpp> #include <boost/mpl/vector_c.hpp> #include <boost/mpl/clear.hpp> #include <boost/mpl/fold.hpp> #include <boost/mpl/copy.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/back_inserter.hpp> #include <boost/mpl/size.hpp> template<class Sequence> struct flatten { typedef typename boost::mpl::fold< Sequence, typename boost::mpl::clear<Sequence>::type, typename boost::mpl::copy< boost::mpl::_2, boost::mpl::back_inserter<boost::mpl::_1> >::type >::type type; }; typedef flatten< boost::mpl::vector< boost::mpl::vector_c<int, 0, 1, 2, 3>, boost::mpl::vector_c<int, 4, 5, 6> > >::type flatvec; int main() { std::cout << boost::mpl::size<flatvec>::value << std::endl; } 8< ------------------------------------------------------------------- It compiles (using gcc 4.2.1), but prints 0 instead of the expected 7. What am I doing wrong? Thanks for your help Andreas
On 09/03/2007 07:46 PM, Andreas Klöckner wrote:
Hi all,
I came up with the following implementation of a "flatten" operation that turns a sequence of sequences into a flat list:
[...]
It compiles (using gcc 4.2.1), but prints 0 instead of the expected 7. What am I doing wrong?
I'm not sure of what you might be doing wrong, but if you take away the lambda expression, and use another level of indirection things work for me: ----- cut ------ #include <iostream> #include <boost/mpl/vector.hpp> #include <boost/mpl/vector_c.hpp> #include <boost/mpl/clear.hpp> #include <boost/mpl/fold.hpp> #include <boost/mpl/copy.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/back_inserter.hpp> #include <boost/mpl/size.hpp> // joins two sequences struct join { template <class Seq1, class Seq2> struct apply { typedef typename boost::mpl::copy< Seq2, boost::mpl::back_inserter<Seq1> >::type type; }; }; template<class Sequence> struct flatten { typedef typename boost::mpl::fold< Sequence, typename boost::mpl::clear<Sequence>::type, join >::type type; }; typedef flatten< boost::mpl::vector< boost::mpl::vector_c<int, 0, 1, 2, 3>, boost::mpl::vector_c<int, 4, 5, 6> > >::type flatvec; int main() { std::cout << boost::mpl::size<flatvec>::value << std::endl; } ----- cut ------ I hope it helps... Did you manage to fix this some other way? Cheers, Tiago -- Tiago de Paula Peixoto <tiago@forked.de>
participants (2)
-
Andreas Klöckner
-
Tiago de Paula Peixoto