std::make_optional
From cppreference.com
| ヘッダ <optional> で定義 |
||
| template< class T > constexpr std::optional<std::decay_t<T>> make_optional( T&& value ); |
(1) | (C++17以降) |
template< class T, class... Args > constexpr std::optional<T> make_optional( Args&&... args ); |
(2) | (C++17以降) |
| template< class T, class U, class... Args > constexpr std::optional<T> make_optional( std::initializer_list<U> il, |
(3) | (C++17以降) |
1) value から optional オブジェクトを作成します。実質的に std::optional<std::decay_t<T>>(std::forward<T>(value)) を呼び出します。
2) args... からインプレースで構築される optional オブジェクトを作成します。 return std::optional<T>(std::in_place, std::forward<Args>(args)...); と同等です。
このオーバーロードは、 std::is_constructible_v<T, Args...> が true の場合にのみ、オーバーロード解決に参加します。
このオーバーロードは、 std::is_constructible_v<T, Args...> が true の場合にのみ、オーバーロード解決に参加します。
3) il と args... からインプレースで構築される optional オブジェクトを作成します。 return std::optional<T>(std::in_place, il, std::forward<Args>(args)...); と同等です。
このオーバーロードは、 std::is_constructible_v<T, std::initializer_list<U>&, Args...> が true の場合にのみ、オーバーロード解決に参加します。
このオーバーロードは、 std::is_constructible_v<T, std::initializer_list<U>&, Args...> が true の場合にのみ、オーバーロード解決に参加します。
目次 |
[編集] Parameters
| value | - | optional オブジェクトの構築に使用する値 |
| il, args | - | T のコンストラクタに渡される引数 |
[編集] Return value
構築された optional オブジェクト。
[編集] Exceptions
T のコンストラクタによってスローされた例外をスローします。
[編集] Notes
保証されたコピー省略のため、オーバーロード (2,3) では T はムーブ可能である必要はありません。
[編集] Example
このコードを実行
#include <iomanip> #include <iostream> #include <optional> #include <string> #include <vector> int main() { auto op1 = std::make_optional<std::vector<char>>({'a','b','c'}); std::cout << "op1: "; for (char c : op1.value()) std::cout << c << ','; auto op2 = std::make_optional<std::vector<int>>(5, 2); std::cout << "\nop2: "; for (int i : *op2) std::cout << i << ','; std::string str{"hello world"}; auto op3 = std::make_optional<std::string>(std::move(str)); std::cout << "\nop3: " << std::quoted(op3.value_or("empty value")) << '\n'; std::cout << "str: " << std::quoted(str) << '\n'; }
実行結果の例
op1: a,b,c, op2: 2,2,2,2,2, op3: "hello world" str: ""
[編集] See also
optional オブジェクトを構築する(public member function) |