Namespaces
Variants

std::make_optional

cppreference.net에서
 
 
유틸리티 라이브러리
일반 유틸리티
관계 연산자 (C++20에서 폐지됨)
정수 비교 함수
(C++20)(C++20)(C++20)    
(C++20)
교체 및 타입 연산
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
공통 어휘 타입
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



 
 
헤더 <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)