Boost logo

Boost :

Subject: Re: [boost] [static_if] Is there interest in a `static if` emulation library?
From: Lorenzo Caminiti (lorcaminiti_at_[hidden])
Date: 2014-09-04 19:08:13


On Wed, Sep 3, 2014 at 9:54 AM, Agustín K-ballo Bergé
<kaballo86_at_[hidden]> wrote:
> On 03/09/2014 01:39 p.m., Robert Ramey wrote:
>>
>> So far I haven't seen anyone propose an example which benefits from the
>> original proposal. Seems to me a solution to a non-existent problem.
>
>
> Purely pseudocode, but I believe the intention of the proposal is to be able
> to do things like:
>
> template< class InputIt, class Distance >
> void advance( InputIt& it, Distance n )
> {
> static_if(is_random_access_iterator<InputIt>()) { it +=n; }
> static_else { /*increment/decrement it in a loop*/ }
> }
>
> ...without having to resort to SFINAE-d overloads nor tag dispatching, given
> that `it += n` is not required to compile for iterators whose category is
> weaker than random access.

Sure, for example:

template< typename Iter, typename Dist >
void myadvance ( Iter& i, Dist n ) {
    Iter* p = &i;
    static_if<is_random_access_iterator<Iter>::value>(
        std::bind([ ] ( auto p, auto n ) {
            *p += n;
        }, p, n)
    ).template elif<is_bidirectional_iterator<Iter>::value>(
        std::bind([ ] ( auto p, auto n ) {
            if(n >= 0) while(n--) ++*p;
            else while(n++) --*p;
        }, p, n)
    ).template elif<is_input_iterator<Iter>::value>(
        std::bind([ ] ( auto p, auto n ) {
            while(n--) ++p;
        }, p, n)
    ).else_(
        std::bind([ ] ( auto false_ ) {
            static_assert(false_, "requires at least InputIterator");
        }, std::false_type())
    );
}

Attached the full example that compiles on clang 3.4.2.

--Lorenzo




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