any_any_cast

any_any_cast (any_cast: any 객체에 저장된 값에 타입 안전하게 접근하기)

이 페이지는 std::any 객체에 저장된 값에 타입 안전하게 접근하는 any_cast 함수에 대해 설명해요. any_cast는 저장된 타입과 요청한 타입이 일치할 때만 값을 반환하고, 그렇지 않으면 예외를 던지거나 포인터를 반환해요. C++17부터 사용할 수 있어요.

출처: cppreference

본문

<any> 헤더에 정의된 any_cast는 저장된 객체에 타입 안전한 접근을 수행해요. U를 std :: remove_cv_t < std :: remove_reference_t < T >>라고 해요.

<any> 헤더에 정의됨
template < class T > T any_cast ( const any & operand ); (1) (since C++17)
template < class T > T any_cast ( any & operand ); (2) (since C++17)
template < class T > T any_cast ( any && operand ); (3) (since C++17)
template < class T > const T * any_cast ( const any * operand ) noexcept ; (4) (since C++17)
template < class T > T * any_cast ( any * operand ) noexcept ; (5) (since C++17)

매개변수

operand - 대상 any 객체

반환 값

예외

예제

#include <any>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>

int main()
{
    // Simple example
    auto a1 = std::any(12);
    std::cout << "1) a1 is int: " << std::any_cast<int>(a1) << '\n';
    
    try
    {
        auto s = std::any_cast<std::string>(a1); // throws
    }
    catch (const std::bad_any_cast& e)
    {
        std::cout << "2) " << e.what() << '\n';
    }
    
    // Pointer example
    if (int* i = std::any_cast<int>(&a1))
        std::cout << "3) a1 is int: " << *i << '\n';
    else if (std::string* s = std::any_cast<std::string>(&a1))
        std::cout << "3) a1 is std::string: " << *s << '\n';
    else
        std::cout << "3) a1 is another type or unset\n";
    
    // Advanced example
    a1 = std::string("hello");
    auto& ra = std::any_cast<std::string&>(a1); // reference
    ra[1] = 'o';
    
    std::cout << "4) a1 is string: "
              << std::any_cast<const std::string&>(a1) << '\n'; // const reference
    
    auto s1 = std::any_cast<std::string&&>(std::move(a1)); // rvalue reference
    // Note: “s1” is a move-constructed std::string:
    static_assert(std::is_same_v<decltype(s1), std::string>);
    
    // Note: the std::string in “a1” is left in valid but unspecified state
    std::cout << "5) a1.size(): "
              << std::any_cast<std::string>(&a1)->size() // pointer
              << '\n'
              << "6) s1: " << s1 << '\n';
}

가능한 출력:

1) a1 is int: 12
2) bad any_cast
3) a1 is int: 12
4) a1 is string: hollo
5) a1.size(): 0
6) s1: hollo

결함 보고

다음 동작 변경 결함 보고서는 이전에 발표된 C++ 표준에 소급 적용되었어요.

DR 적용 대상 게시된 동작 올바른 동작
LWG 3305 C++17 T가 void인 경우 오버로드 ( 4,5 )의 동작이 불명확했음 이 경우 프로그램이 ill-formed임

더 알아보기 (Learn more)

cppreference