Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable the C/C++ "Conditional with Omitted Operand" (aka Elvis Operator "?:") in GCC

In the talk Non-conforming C++ from CppCon2019 it is introduced the "Elvis Operator" in C++, which is a non-standard extension supported by many compilers.

It works by omitting the middle operand of an ?: expression:

std::shared_ptr<foo> read();
std::shared_ptr<foo> default_value();

auto read_or_default()
{
    return read() ?: default_value();
}

This is exactly the sample taken from slide 11 of the presentation.

However when I build it on GCC 7.4.0 on Ubuntu 18.04, or with GCC 8.2.0 on MinGW, using the -std=gnu++14 flag, I get this error:

error: lvalue required as unary '&' operand
     return read() ?: default_value();
                                    ^

In the talk it is said that this extension is present in GCC at least since version 4.1.2.

So what's wrong?

like image 216
lornova Avatar asked Feb 01 '26 03:02

lornova


1 Answers

It is not the basic "conditionals with omitted operand" feature that fails. It's the combination with std::shared:ptr that's triggering a bug in GCC fixed in GCC 9.1.

The below code works since GCC 4.1.2:

int read();
int default_value();

int read_or_default()
{
    return read() ?: default_value();
}
like image 63
Pibben Avatar answered Feb 02 '26 16:02

Pibben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!