Boost logo

Boost :

From: Aleksey Gurtovoy (agurtovoy_at_[hidden])
Date: 2003-07-11 11:34:29


Drazen DOTLIC wrote:
> Hello,

Hi Drazen,

> I've recently discovered that mpl provides all the functionality
> I was previously using from loki, so I decided to switch. There
> is one small thing driving me crazy, and I was wondering if I
> missed something...
> I was using loki's TypeAtNonStrict "algorithm" to give me type
> from type list at a specified position, or NullType (loki's
> internal "null" class) if not found. Now, I need the same for
> mpl:vector, and I tried the following 'naïve' approach:
>
> [TypeVector is boost::mpl::vector<bool>]
> enum { numParams = boost::mpl::size<TypeVector>::type::value };
> typedef typename boost::mpl::if_c<(numParams > 2),
> typename boost::mpl::at_c<TypeVector, 2>::type,
> boost::mpl::void_>::type Param1;
>
> I was expecting to get Param1 to be boost::mpl::void_, but to my
> great surprise, my compiler (VC7.1) decided to fully evaluate
> "then" branch of if_c as well, even though the expression
> numParams > 2 was false, and failed.

It's a pitfall that is easy to fall into even if you've read about
it. The correct way to implement what you want would be

    typedef typename boost::mpl::apply_if_c<(numParams > 2),
        boost::mpl::at_c<TypeVector, 2>,
        boost::mpl::identity<boost::mpl::void_>
>::type Param1;

We have a whole section in the docs devoted to this issue -
http://www.boost.org/libs/mpl/doc/index.html#applyif

> What would be the "right" way to express my intention? Btw, I
> would like to congratulate authors of mpl on the job well done, I am
> most impressed not only with the features that mpl provides but also
> with the errors I get when something goes wrong - they are far more
> readable than most of the STL errors I am used to seeing.

Thank you!

As Dave already mentioned, if you want to see really pretty errors :),
you might want to consider to install STLFilt - see
http://www.bdsoft.com/dist/vcmeta-demo.txt for the MPL-specific example.

HTH,
Aleksey


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk