std::make_optional
来自 zh.cppreference.net
| 定义于头文件 <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 创建一个可选对象。实际调用 std::optional<std::decay_t<T>>(std::forward<T>(value))。2) 创建一个从
该重载仅当
args... 原位构造的可选对象。等价于 return std::optional<T>(std::in_place, std::forward<Args>(args)...);。该重载仅当
std::is_constructible_v<T, Args...> 为 true 时参与重载决议。
3) 创建一个从
该重载仅当
il 和 args... 原位构造的可选对象。等价于 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
构造函数的参数
|
返回值
构造的可选对象。
异常
抛出
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
对象
(公开成员函数) |