ibs*_*bse 3 c++ boost optional c++11
是一种初始化可选的方法,如:
bool conditional = true;
boost::optional<int> opt = conditional ? 5 : boost::none;
Run Code Online (Sandbox Code Playgroud)
为什么会出现错误?:
main.cpp:31:31: error: operands to ?: have different types ‘int’ and ‘const boost::none_t’
boost::make_optional(cond ? 5 : boost::none);
| ~~~~~^~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
用简单的if else我可以做到这一点:
boost::optional<int> opt;
if (cond)
opt = 5;
else
opt = boost::none;
Run Code Online (Sandbox Code Playgroud)
三元运算符要求左右为相同(或可转换)类型。none_t并且int不是同一类型。你大概可以做cond ? boost::optional<int>(5) : boost:none
我不使用 boost,所以只是猜测基于 的语法std::optional,但以下确实有效:
std::optional<int> opt = cond ? std::optional<int>(5) : std::nullopt;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
194 次 |
| 最近记录: |