프로그래밍/Morden C++

[C++17] std::optional

MAKGA 2021. 7. 17. 21:48
320x100

std::optional은 값을 저장하거나 값이 없는 상태를 저장할 수 있다.

 

cppreference 예제

#include <string>
#include <functional>
#include <iostream>
#include <optional>
 
// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b) {
    if (b)
        return "Godzilla";
    return {};
}
 
// std::nullopt can be used to create any (empty) std::optional
auto create2(bool b) {
    return b ? std::optional<std::string>{"Godzilla"} : std::nullopt;
}
 
// std::reference_wrapper may be used to return a reference
auto create_ref(bool b) {
    static std::string value = "Godzilla";
    return b ? std::optional<std::reference_wrapper<std::string>>{value}
             : std::nullopt;
}
 
int main()
{
    std::cout << "create(false) returned "
              << create(false).value_or("empty") << '\n';
 
    // optional-returning factory functions are usable as conditions of while and if
    if (auto str = create2(true)) {
        std::cout << "create2(true) returned " << *str << '\n';
    }
 
    if (auto str = create_ref(true)) {
        // using get() to access the reference_wrapper's value
        std::cout << "create_ref(true) returned " << str->get() << '\n';
        str->get() = "Mothra";
        std::cout << "modifying it changed it to " << str->get() << '\n';
    }
}

 

결과

create(false) returned empty
create2(true) returned Godzilla
create_ref(true) returned Godzilla
modifying it changed it to Mothra

 

 

출처: https://en.cppreference.com/w/cpp/utility/optional

 

std::optional - cppreference.com

template< class T > class optional; (since C++17) The class template std::optional manages an optional contained value, i.e. a value that may or may not be present. A common use case for optional is the return value of a function that may fail. As opposed

en.cppreference.com

 

 

다른 사용 예제

std::optional<std::string> fnString(bool b)
{
	if (b) {
		return std::string("test");
	}
	return std::nullopt;
}



std::optional<std::string> opt = fnString(true);
// 두 조건이 같은 의미
if (opt || opt.has_value()) {
	std::cout << opt.value() << std::endl;
}

 

optional에 참조를 사용하면 에러가 난다

A a;
std::optional<A&> opt = a;

 

다음과 같이 바꿔 작업한다.

A a;
std::optional<std::reference_wrapper<A>> maybe_a = std::ref(a);

 

 

자세한 설명: https://modoocode.com/309

 

씹어먹는 C++ - <17 - 5. C++ 17 의 std::optional, variant, tuple 살펴보기>

 

modoocode.com

 

320x100

'프로그래밍 > Morden C++' 카테고리의 다른 글

std::clamp  (0) 2021.09.29
std::accumulate  (0) 2021.09.22
std::splice  (0) 2021.07.13
std::advance  (0) 2021.07.13
자주 쓰이는 vector 사용 패턴  (0) 2021.07.11