Boost logo

Boost Users :

Subject: Re: [Boost-users] Tuples: Can someone help me generalize this?
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2008-09-10 12:14:04


AMDG

Derrick Hathaway wrote:
> Hello, boost-users,
> what I am trying to accomplish is a generic collection of N objects of
> type Type. I need for the N objects to be tightly packed and I would
> like the collection to be constructible in this way:
>
> uniform_vector<3, float> my_point(1.0f, 2.1f, 3.2f);
>
> I'm very new to the template (meta)programming scene and I would like
> to get better at it, so any advice you could give that would be
> instructive in that regard would be much appreciated. The code below
> is what I have come up with.
>
> Question 1: Am I reinventing the wheel at all? In other words is there
> something I can just typedef to get this functionality?
>
> Question 2: If not, how could I generalize this? Is there a template
> metaprogramming way? I'm sure it can be done with the preprocessor but
> I'm no good with macros... but then again I'm not much good with
> templates either at least not by a boost mailing list standard anyway. :)

Here's some template code that creates an appropriate tuple type.

#include <boost/mpl/transform.hpp>
#include <boost/mpl/always.hpp>
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/back_inserter.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/mpl.hpp>

#include <iostream>

// create a sequence of 5 elements
typedef boost::mpl::range_c<int, 0, 5> range;
// convert all the elements to float and make the result a fusion vector.
typedef boost::mpl::transform<range, boost::mpl::always<float>,
    boost::mpl::back_inserter<boost::fusion::vector<> > >::type tuple_type;

int main() {
    tuple_type t(0, 1, 2, 3, 4);
    std::cout << typeid(tuple_type).name() << std::endl;
}

In Christ,
Steven Watanabe


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