Namespaces
Variants

std::make_optional

ja.cppreference.net より
 
 
ユーティリティライブラリ
言語サポート
型サポート (基本型、RTTI)
ライブラリ機能テストマクロ (C++20)
プログラムユーティリティ
可変引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)    
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)(C++20)(C++20)    
(C++20)
swap と 型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
共通のボキャブラリ型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



 
 
ヘッダ <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オブジェクトを構築する
(公開メンバ関数)