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

3.1k Views Asked by At

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?

1

There are 1 best solutions below

0
Pibben On BEST ANSWER

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();
}