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 时才会参与重载决议。

参数

value-构造 optional 对象所用的值
il, args-传递给 T 构造函数的实参

返回值

构造的 optional 对象。

异常

抛出 T 的构造函数所抛的任何异常。

注解

因为受保证的复制消除,对于重载 (2,3) T 不需要可移动。

示例

#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: " << 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 对象
(公开成员函数)