C++ Logo

STD-PROPOSALS

Advanced search

Subject: [std-proposals] Initial Idea of Indirect If Statement
From: Andrew Tomazos (andrewtomazos_at_[hidden])
Date: 2019-10-26 11:14:51


We propose a new variant of the if statement that fuses a condition
declaration with an indirection in the true branch. We call it an
'indirect if statement'.

An indirect if statement of the form:

    if (DECL : EXPR) X else Y;

is equivalent to:

    {
        auto&& __c = EXPR;
        if (__c) {
            DECL = *__c;
            X;
        } else {
            Y; // noteworthy: DECL is not in scope here
        }
    }

So for example:

int* get();

int main() {
    if (int x : get())
        return x;
    else
        return EXIT_FAILURE;
}

void f(std::variant<A,B,C> V) {
    if (auto x : std::get_if<A>(V)) {
       /*...*/
    } else if (auto x : std::get_if<B>(V)) {
       /*...*/
    } else if (auto x : std::get_if<C>(V)) {
       /*...*/
    }
}

template<typename D, typename B>
D* derived_if(B& b) {
      return dynamic_cast<D*>(&b);
}

void g(Animal& a) {
    if (auto& dog : derived_if<Dog>(a)) {
        /* ... */
    } else if (auto& cat : derived_if<Cat>(a)) {
        /* ... */
    } else if (auto& pig : derived_if<Pig>(a)) {
        /* ... */
    }
}

T* ptr;
std::optional<T> opt;
std::shared_ptr<T> sptr;
std::unique_ptr<T> uptr;

int main() {
    if (T x : ptr)
        /*...*/;

    if (T x : opt)
        /*...*/;

    if (T x : sptr)
        /*...*/;

    if (T x : uptr)
        /*...*/
}

The motivation should be self-evident enough from the examples for this
first note.

Initial thoughts appreciated.
   -Andrew.



STD-PROPOSALS list run by std-proposals-owner@lists.isocpp.org

Standard Proposals Archives on Google Groups