Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ macro expression containing return (like Rust's try!)

Tags:

c++

macros

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

Something like this:

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 it doesn't work because return is a statement not an expression. There are other problems with the above code but it roughly gives an idea of what I want. Does anyone have any bright ideas?

like image 422
Timmmm Avatar asked Oct 18 '22 14:10

Timmmm


1 Answers

Thanks to NathanOliver's link it looks like you can do it with statement expressions which are apparently only supported by Clang and GCC. Something like this:

#define TRY(x)                                                     \
    ({                                                             \
        auto& ref = (x);                                           \
        if (!ref.ok) {                                             \
            return -1;                                             \
        }                                                          \
        ref.value; // The block evaluates to the last expression.  \
    })
like image 81
Timmmm Avatar answered Nov 15 '22 06:11

Timmmm