Programming

(C++) variant와 monostate

steloflute 2023. 9. 7. 00:48

variant의 첫 번째 타입으로 monostate를 주면 variant 자체에 디폴트 값이 생겨서 디폴트 값을 부여하지 않아도 된다.

 

예제:

#include <cassert>
#include <iostream>
#include <variant>
 
struct S
{
    S(int i) : i(i) {}
    int i;
};
 
int main()
{
    // Without the monostate type this declaration will fail.
    // This is because S is not default-constructible.
    std::variant<std::monostate, S> var;
    assert(var.index() == 0);
 
    try
    {
        std::get<S>(var); // throws! We need to assign a value
    }
    catch(const std::bad_variant_access& e)
    {
        std::cout << e.what() << '\n';
    }
 
    var = 42;
    std::cout << "std::get: " << std::get<S>(var).i << '\n'
              << "std::hash: " << std::hex << std::showbase
              << std::hash<std::monostate>{}(std::monostate{}) << '\n';
}

 

출처: std::monostate - cppreference.com

 

std::monostate - cppreference.com

struct monostate { }; (since C++17) Unit type intended for use as a well-behaved empty alternative in std::variant. In particular, a variant of non-default-constructible types may list std::monostate as its first alternative: this makes the variant itself

en.cppreference.com