std::any

alysion “alysion”·2023년 11월 27일

std::any는 모든 유형의 단일 값에 대해 유형이 안전한 컨테이너를 제공하는 C++17에 도입된 C++ 표준 라이브러리 클래스 템플릿

std::any 형식의 객체에는 '아무(any)' 형식의 값을 담을 수 있음. 단 복사가 가능한(copyable)형식 이어야 한다

1. 용법

아래 header를 포함하여 사용 가능.

#include <any>

2. 선언 및 초기화

std::any 객체를 선언하고 모든 유형의 값으로 초기화 할 수 있음

#include <any>

std::any myAny = 42; // Initialized with an int

3. 새 값 할당

myAny = 3.14; // Assigned a double value

4. 값 지우기

myAny = std::any(); // Clears the stored value

5. 값 탐색

if (myAny.type() == typeid(int)) {
    int value = std::any_cast<int>(myAny);
    // Use 'value' as an int
}

try {
    int value = std::any_cast<int>(myAny);
    // Use 'value' as an int
} catch (const std::bad_any_cast& e) {
    // Handle the case where the type doesn't match
}
profile
다음에 다시 쓸게요

0개의 댓글