Boost logo

Boost Users :

From: Ovanes Markarian (om_boost_at_[hidden])
Date: 2007-01-04 06:06:46


Johan,

there is an mpl::for_each construct to do this. Unfortunately for_each is not documented, but it
is a part of mpl library. If you have the MPL book from Dave and Alexey you can read about it on
page 175. On page 176-179 you will find 3 differnt examples about type printing. Below is one of
the approaches converted to you example:

Your example should work with the following sample:

#include <iostreams>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/placeholders.hpp>

namespace mpl = boost::mpl;

template<class T>
struct Type2Type {}; //this will prevent instantiation of every type
                     // and transport the type information only
                     // => Type2Type is only 1 byte big => cheaper as a reference or ptr

struct WriteSize
{
    template<class T>
    void operator() (Type2Type<T> t)
    {
        std::cout << sizeof(T) << " ";
    }
};

typedef mpl::vector<float,double,long double> SomeVector;

//now the call to for_each
mpl::for_each<SomeVector, Type2Type<mpl::_1> >(WriteSize());

With Kind Regards,

Ovanes Markarian

On Thu, January 4, 2007 11:34, Johan Torp wrote:
> I would like to generate one call to a templated function for each type
> in an MPL sequence. Which is the best way to do this?
> E.g.:
>
> typedef vector<float,double,long double> SomeVector;
> template <typename T> write_size() { std::cout << sizeof(T) << " "; }
>
> Should somehow expand to:
>
> write_size<float>();
> write_size<double>();
> write_size<long double>();
>
> I have managed to do this "manually" in a fairly general way, what I'm
> looking for is some part of boost which replaces my ForEach struct below
> or some nicer way of writing the same code:
>
> ==============================================
> struct WriteSize
> {
> template<typename T> void Call() {write_size<T>();}
> };
>
> template <class It, class End> struct ForEach
> {
> template <class Func> static void Call(Func& func)
> {
> func.Call<typename It::type>();
> ForEach<typename next<It>::type, End>::Call(func);
> }
> };
>
> template <class End> struct ForEach<End, End>
> {
> template <class Func> static void Call(Func&) {}
> };
>
> // Then I can generate the calls by
> WriteSize ws;
> ForEach<begin<SomeVector;>::type, end<SomeVector;>::type>::Call(ws);
>
> ==============================================
>
> --
> System Developer
> TouchTable AB
> Tel: +46 (0)31 773 68 12
> johan.torp_at_[hidden]
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>


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