现代cpp特性
Casting 类型转换
static_cast<>(): 在相关的 numeric types 之间或者 ptr 之间转换dynamic_cast<>(): 用于多态继承, 例如将 parent 转换成 child 之类reinterpret_cast<>(): 任意转变const_cast<>(): 将一个表达式变成常量表达式
std::optional 选项库
-
表示一个可能有值的对象(没有值时就是默认的std::nullopt)
- 例子
std::optional<int> even_value = is_even ? std::optional<int>(128) : std::nullopt;
- 例子
-
判断 std::optional 对象是否有值可以用 has_value函数, 或者判断是否不等于std::nullopt, 或者直接用if语句对对象进行判断
-
std::optional<int> result1 = find_the_first_postive_value(pos_values); if (result1.has_value()) { std::cout << result1.value() << std::endl; } if (result1 != std::nullopt) { std::cout << result1.value() << std::endl; } if (result1) { std::cout << result1.value() << std::endl; }1
2
3
4
5
6
7
8
- 如果想在std::optional对象为std::nullopt的情况下设置默认值的话,可以用value_or 函数
- ```cpp
std::optional<int> val9 = std::nullopt;
std::cout << val9.value_or(-1) << std::endl; // 输出 -1
val9.emplace(128); // optional 的插值用 emplace()
std::cout << val9.value_or(-1) << std::endl; // 输出 128
-
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
