Boost logo

Boost Users :

Subject: Re: [Boost-users] C++ guru required!
From: Nathan Ridge (zeratul976_at_[hidden])
Date: 2012-02-19 18:28:19


> >> Assuming
> >> I'm correct and that Andrei's use cases don't make the case for
> >> static if - Is there a real case for static if.
> >
> > Yes. Here's an example:
> >
> > template <typename Iterator>
> > void advance(Iterator it, size_t n)
> > {
> > static_if(iterator_category<it>::type == random_access_category_tag)
> > {
> > it += n;
> > }
> > else
> > {
> > for (size_t i = 0; i < n; ++i)
> > ++it;
> > }
> > }
> >
> > Were one to use a runtime if instead, and instantiate the function
> > with an iterator that is not random access, one would get a compiler
> > error of the form 'no match for operator+=(Iterator, size_t)'.
> >
> > The idea is that with a runtime if, the compiler type-checks the
> > unused branch even if it ends up eliminating it in later on in the
> > optimization phase.
>
> Well, this seems like a better example, but ...
>
> the following wouldn't compile anyway as if can't compare types.
>
> if(iterator_category<it>::type == random_access_category_tag)

You're right, of course. It should have been something like

is_same<iterator_category<Iterator>::type, random_access_category_tag>::value

> Anyway, one could right right now:
>
> if(is_random_access_iterator<Iterator>::value){
> it += n;
> }
> else{
> for(size_ti = 0; i < n; ++i){
> ++it;
> }
>
> IF the compiler skipped the "false" branch. I would guess this
> behavior is undefined (but maybe not). So maybe everything
> would be just fine if behavior in this case were defined to skip
> branches known to be false at compile time.

I'm not sure whether compilers are required by the standard to
type-check branches known not to be taken at compile time, but in
practice I think they do because type-checking is done at an
earlier stage of compilation than optimizations like constant
propagation.

Regards,
Nate
                                               


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