C ++ macro expression containing return (e.g. Rust try!)

Rust has a macro, which is an expression that either evaluates to a value or returns a function. Is there a way to do this in C ++?

Something like that:

struct Result
{
    bool ok;
    int value;
}

Result foo() { ... }

#define TRY(x) (auto& ref = (x), ref.ok ? ref.value : return -1)

int main()
{
    int i = TRY(foo());
}

Unfortunately, this does not work because it returnis an expression, not an expression. There are other problems with the above code, but it roughly gives an idea of ​​what I want. Anyone have any bright ideas?

+4
source share
1 answer

NathanOliver , , , -, Clang GCC. - :

#define TRY(x)                                                     \
    ({                                                             \
        auto& ref = (x);                                           \
        if (!ref.ok) {                                             \
            return -1;                                             \
        }                                                          \
        ref.value; // The block evaluates to the last expression.  \
    })
+2

Source: https://habr.com/ru/post/1673603/


All Articles