名稱空間
變體
操作

std::make_optional

來自 cppreference.com
< cpp‎ | utility‎ | optional
 
 
 
 
定義於標頭檔案 <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 時參與過載決議。

目錄

[edit] 引數

value - 用於構造 optional 物件的值
il, args - 傳遞給 `T` 建構函式的引數

[edit] 返回值

構造的 optional 物件。

[edit] 異常

丟擲 `T` 的建構函式丟擲的任何異常。

[edit] 注意

由於保證了複製省略,`T` 對於過載 (2,3) 無需可移動。

[edit] 示例

#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: ""

[edit] 參閱

構造 optional 物件
(public member function) [編輯]
English 日本語 中文(简体) 中文(繁體)