|
Boost Users : |
From: Terje Slettebų (tslettebo_at_[hidden])
Date: 2003-02-24 15:39:43
>From: "Markus Werle" <yg-boost-users_at_[hidden]>
> I am trying to migrate some parts of my code from
> loki to boost::mpl.
>
> Q1: which is the best way to perform nested if-then-else?
>
> Assume given "values":
> bool B1, bool B2;
> class ff, class tf, class ft, class tt;
>
> I replaced
>
> -----------------------------------------------------------
> typedef typename
> Loki::Select<B1,
> typename Loki::Select<B2, tt, tf>::Result,
> typename Loki::Select<B2, ft, ff>::Result
> >::Result type;
> -----------------------------------------------------------
>
> with
>
> typedef typename
> apply_if
> <
> bool_c<B1>,
>
> apply_if
> <
> bool_c<B2>,
> identity<tt>,
> identity<tf>
> >,
>
> apply_if
> <
> bool_c<B2>,
> identity<ft>,
> identity<ff>
> >
> >::type type;
>
> Q2: Is apply_if always to be preferred over if_?
mpl::if_ is the same as Loki::Select (actually, mpl::if_c is). mpl::apply_if
does a "::type" on the result. Thus, the following two are equivalent:
mpl::if_<...>::type::type
mpl::apply_if<...>::type
This is useful for delaying evaluation. For example:
// Add reference if "flag" is true
typedef mpl::if_c<flag,
boost::add_reference<T>::type,
T
>::type new_type;
If T is void, the above will give an error (reference to void), even if
"flag" is false. This is because "add_reference<T>::type" instantiates the
template, regardless of the outcome of the if_c. However, if you instead do
it like this:
typedef mpl::if_c<flag,
boost::add_reference<T>,
mpl::identity<T>
>::type::type new_type;
then there won't be a problem, because add_reference<T> doesn't get
instantiated in this case. The above may be written as:
typedef mpl::apply_if_c<flag,
boost::add_reference<T>,
mpl::identity<T>
>::type new_type;
Thus, this is an important idiom: Preventing eager evaluation of the
arguments. apply_if just gives a handy way of doing it. If you don't need
this, then if_ can be used just as well.
> Q3: (OT) Is there a mpl-equivalent to run-time case?
I don't think so. That could be a good addition.
Regards,
Terje
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