Guillaume Paris
Guillaume Paris

Reputation: 10537

need explanation on boost::mpl

typedef vector<long,float,short,double,float,long,long double> types;
typedef fold<
      types
    , int_<0>
    , if_< is_float<_2>,next<_1>,_1 >
    >::type number_of_floats;

BOOST_MPL_ASSERT_RELATION( number_of_floats::value, ==, 4 );

I don't understand the way fold works, why int_<0>? why is_float<_2> ?

Could someone give me some clues to understand this "function" ? thanks

Upvotes: 1

Views: 255

Answers (1)

pmr
pmr

Reputation: 59841

int_<0> is the starting value of the accumulator used for the fold. Try to use int_<1> and see what happens.

The third argument is the operator used to fold the sequence. This needs to be a binary metafunction. if_< is_float<_2>,next<_1>,_1 > is turned into a lambda expression with two arguments where _1 and _2 refer to the first and second argument this lambda expression takes.

The predicate is_float<_2> returns true if the second argument to if_ is a float. _2 is a placeholder. Placeholders refer to the n-th argument of the template specialization.

next<_1> simply returns the next value of the current state (e.g. next<int_<0>> == int_<1>).

If the predicate returns false we simply return _1 which is the unaltered state.

Try to understand what a fold is first, then try to understand the boost::mpl way of doing it.

A simple exercise is to write a fold that return the length of the vector.

Upvotes: 3

Related Questions