命名空间
变体
操作

std::make_optional

来自 cppreference.cn
< 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: " << 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 对象
(公共成员函数) [编辑]