2

I'm pretty new to Boost fusion and maybe my question does not make any sense. Fusion is presented as : "the fusion between runtime and compile time algorithms". I think i'm getting lost between what is done at compile time and what is done at run time in fusion.

Lets take the for_each template, in fact they are two! the function and the metafunction. The metafunction looks like to me as a trait class template for the for_each function, wrong?.

taking the example of the for_each function :

struct increment
{
    template<typename T>
    void operator()(T& t) const
    {
        ++t;
    }
};

vector<int,int> vec(1,2);
for_each(vec, increment());

I understand that the for_each loop will be unfolded at compile time to produce code like

++at_c<0>(vec); 
++at_c<1>(vec);

(obviously the at_c<x> templates will also generate code to access fusion vector members)

To me, both the for_each function and metafunction are "compile time programs", wrong again?

Can someone explain me (with a simple example) what part of boost fusion is just compile time meta-programm and what is just classical compile time code?

Laurent
  • 812
  • 5
  • 15

1 Answers1

2

boost::fusion is about the manipulation of heterogeneous collections of types. In C++, handling of types is handled at compile time (metafunctions), while value manipulation is predominately handled at runtime (functions).

If you look closely at the documentation in boost::fusion, you will see that metafunctions return things like ...::type. These types have to be handled at compile time.

In C++, there is something like RTTI (Run Time Type Information), but for the most part, it's ability is relegated to identifying the type of something at runtime. There is no type manipulation available at runtime.

So, type manipulation has to be dealt with at compile time. Imperative programming constructs aren't useful at compile time. C++ compile time constructs are more akin to functional programming constructs. I'm taking the long way to say that boost::fusion::for_each is an algorithm for unwinding loops at compile time so that all types in the sequence are visible 'in a linear fashion' at compile time.

Values for each type is then a dereference at runtime to the type.

So coming full circle, the boost::fusion::for_each function provides the value, and the boost::fusion::for_each metafunction returns a type, which could be useful for indirection through a functor for obtaining the associated value.

  • Ok, thanks Raymond, I think my question mainly reflects my ignorance of fusion. I will shorten it in order to make it usefull for other fusion newbies. – Laurent Nov 24 '13 at 14:12