lor*_*ova 3 c++ gcc conditional-operator elvis-operator
在 CppCon2019 的演讲Non-conforming C++中,介绍了 C++ 中的“ Elvis Operator ”,这是许多编译器支持的非标准扩展。
它的工作原理是省略表达式的中间操作数?::
std::shared_ptr<foo> read();
std::shared_ptr<foo> default_value();
auto read_or_default()
{
return read() ?: default_value();
}
Run Code Online (Sandbox Code Playgroud)
这正是从演示文稿的幻灯片 11 中截取的示例。
然而,当我在 Ubuntu 18.04 上的 GCC 7.4.0 上构建它,或者在 MinGW 上使用 GCC 8.2.0 构建它时,使用该-std=gnu++14标志,我收到此错误:
error: lvalue required as unary '&' operand
return read() ?: default_value();
^
Run Code Online (Sandbox Code Playgroud)
在演讲中据说这个扩展至少从 4.1.2 版本开始就存在于 GCC 中。
那么出了什么问题呢?
失败的并不是基本的“省略操作数的条件”功能。正是它的组合std::shared:ptr触发了 GCC 中的一个错误,该错误已在 GCC 9.1 中修复。
以下代码自 GCC 4.1.2 起有效:
int read();
int default_value();
int read_or_default()
{
return read() ?: default_value();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3036 次 |
| 最近记录: |