template <class U> constexpr T value_or(U&& v) const&; // (1) template <class U> constexpr T value_or(U&& v) &&; // (2)
概要
有効値もしくは指定された無効値を取得する。
この関数は、*this
が有効値を保持していれば有効値を返し、そうでなければv
を返す。
要件
is_move_constructible_v<T> == true
であることis_convertible_v<U&&, T> == true
であること
効果
以下の式と等価の効果を持つ:
return has_value() ? value() : static_cast<T>(std::forward<U>(v));
例
#include <iostream> #include <optional> int main() { std::optional<int> p1 = 3; // p1が有効値を持っていればそれが返り、持っていなければ-1が返る int result1 = p1.value_or(-1); std::cout << result1 << std::endl; std::optional<int> p2; int result2 = p2.value_or(-1); std::cout << result2 << std::endl; }
出力
3
-1
バージョン
言語
- C++17
処理系
- Clang: 4.0.1
- GCC: 7.2
- ICC: ??
- Visual C++: ??