std:: make_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,
|
(3) | (C++17 起) |
此重载仅当 std:: is_constructible_v < T, Args... > 为 true 时参与重载决议。
仅当 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
对象
(公开成员函数) |