Boost logo

Boost Users :

Subject: Re: [Boost-users] Variant and Fusion
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2010-03-11 13:33:39


AMDG

Matthias Vallentin wrote:
>> I think the easiest way is probably to create a runtime
>> iterator that walks over the vector and recurses into
>> any variants that it contains.
>>
>> Then you can use fusion's
>> algorithms to iterate over the fusion::vector and the
>> vector in parallel.
>>
>
> I'm not sure if I can follow. If I start with the variant and have some
> plan to partition it into sequences, how would I use an iterator rather
> a visitor? Would you mind illustrating your idea with a small code
> snippet?
>

Actually making an iterator is rather a pain. It's probably easiest to copy
the variant into a flattened vector like this.

#include <boost/variant.hpp>
#include <vector>
#include <algorithm>

template<class Iter>
class visitor {
public:
    typedef void result_type;
    visitor(Iter& iter) : out(&iter) {}
    template<class T>
    void operator()(T& t) const {
        *(*out)++ = &t;
    }
    template<class T>
    void operator()(std::vector<T>& v) const {
        std::for_each(v.begin(), v.end(), boost::apply_visitor(*this));
    }
    Iter* out;
};

template<class V, class Iter>
Iter flatten_variant(V& v, Iter out) {
    boost::apply_visitor(visitor<Iter>(out), v);
    return out;
}

int main() {
    boost::make_recursive_variant<
        int,
        double,
        std::vector<boost::recursive_variant_>
>::type v;
    std::vector<boost::variant<int*, double*> > temp;
    flatten_variant(v, std::back_inserter(temp));
}

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