名前空間
変種
操作

std::make_optional

From cppreference.com
< cpp‎ | utility‎ | optional
 
 
ユーティリティライブラリ
言語サポート
型のサポート (基本型、RTTI)
ライブラリ機能検査マクロ (C++20)
プログラムユーティリティ
可変引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)  
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
 
 
ヘッダ <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) ilargs... からインプレースで構築される optional オブジェクトを作成します。 return std::optional<T>(std::in_place, il, std::forward<Args>(args)...); と同等です。
このオーバーロードは、 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) [編集]
English 日本語 中文(简体) 中文(繁體)