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?
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. \
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With