optional_make_optional
optional_make_optional (std::make_optional 헬퍼 함수)
이 페이지는 C++17부터 사용할 수 있는 std::make_optional 함수에 대해 다뤄요. 이 함수는 주어진 값이나 생성자 인자를 바탕으로 std::optional 객체를 간편하게 생성해 주는 헬퍼 함수예요. 세 가지 오버로드를 제공해서 다양한 상황에서 유연하게 사용할 수 있어요.
출처: cppreference
본문
<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부터) |
매개변수 (Parameters)
| value | - | optional 객체를 생성할 값이에요. |
|---|---|---|
| il, args | - | T의 생성자에 전달할 인자들이에요. |
반환값 (Return value)
생성된 optional 객체를 반환해요.
예외 (Exceptions)
T의 생성자가 던지는 모든 예외를 그대로 전파해요.
참고 사항 (Notes)
(2), (3) 오버로드는 보장된 복사 생략(guaranteed copy elision) 덕분에 T가 이동 가능(movable)하지 않아도 돼요.
예제 (Example)
#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: ""
같이 보기 (See also)
| (constructor) | optional 객체를 생성하는 public 멤버 함수예요. [편집] |
|---|