Namespaces
Variants

std:: make_optional

From cppreference.net
Utilities library
헤더 파일에 정의됨 <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) il args... 로부터 제자리에서 생성된 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 의 생성자가 던지는 모든 예외를 던집니다.

참고 사항

T 는 보장된 복사 생략으로 인해 오버로드 ( 2,3 ) 에 대해 이동 가능할 필요가 없습니다.

예제

#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 객체를 생성합니다
(public member function)