Search code examples
c++templatesboost-fusion

Initializing the elements of a Boost.Fusion sequence from another sequence


I've got a Boost.Fusion sequence of elements that need to be initialized one each with the elements of another sequence. When I'd not use Fusion, this would look like:

class A {
    A1 a;
    A2 b;
    A3 c;
};

class B {
    B1 a; 
    B2 b;
    B3 c;

    B( const A& o ) : a(o.a), b(o.b), c(o.c) {}
};

My only idea to realize this with Fusion vectors is something like

BVector b( transform( AVector(), magic_functor() ) );

In this idea, magic_functor would have a result type of Bi for an Ai and perform the construction in its operator(). However, magic_functor would have to know the right type to cast to, which would result in duplicate logic.

Is there any better way of fusion-ifying the initialization?


Solution

  • If I understand correctly, you want to replace your classes with fusion::vectors, like this:

    typedef boost::fusion::vector<A1, A2, A3> A;
    typedef boost::fusion::vector<B1, B2, B3> B;
    

    In this case, you can initialize B from A simply by using vector's "copy" constructor (it is not a real copy constructor since it can accept any forward sequence):

    A a(A1(...), A2(...), A3(...)); // instance of A
    B b(a);                         // each element of b is initialized from the 
                                    //corresponding element in a
    

    It should be noted that A and B does not even need to be the same kind of sequence: you can initialize a fusion::vector from a fusion::list, or a fusion::set from a myCustomForwardSequence.