std::make_optional
ja.cppreference.net より
| ヘッダ <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,
Args&&... args );
|
(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 である場合にのみオーバーロード解決に参加します。
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 である場合にのみオーバーロード解決に参加します。
パラメータ
| value | - | オプショナルオブジェクトを構築する値 |
| il, args | - |
T
のコンストラクタに渡される引数
|
戻り値
構築されたオプショナルオブジェクト。
例外
Tのコンストラクタによってスローされるあらゆる例外をスローします。
注記
T
は、保証されたコピー省略により、オーバーロード
(
2,3
)
では movable である必要はありません。
例
このコードを実行
#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: ""
関連項目
optionalオブジェクトを構築する
(公開メンバ関数) |