Namespaces
Variants

std::any_cast

cppreference.net에서
 
 
유틸리티 라이브러리
일반 유틸리티
관계 연산자 (C++20에서 비권장)
정수 비교 함수
(C++20)(C++20)(C++20)    
(C++20)
스왑 및 타입 연산
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
공통 어휘 타입
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



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

포함된 객체에 대한 타입 안전 접근을 수행합니다.

U 을(를) std::remove_cv_t<std::remove_reference_t<T>> 이라고 합시다.

1) std::is_constructible_v<T, const U&> 이(가) false 인 경우 프로그램의 형식이 잘못되었습니다.
2) std::is_constructible_v<T, U&> 이(가) false 인 경우 프로그램의 형식이 잘못되었습니다.
3) std::is_constructible_v<T, U> 이(가) false 인 경우 프로그램의 형식이 잘못되었습니다.
4,5) std::is_void_v<T> 이(가) true 인 경우 프로그램의 형식이 잘못되었습니다.

매개변수

피연산자 - 대상 any 객체

반환값

1,2) 반환값 static_cast < T > ( * std :: any_cast < U > ( & operand ) ) .
3) 반환값 static_cast < T > ( std :: move ( * std :: any_cast < U > ( & operand ) ) ) .
4,5) 만약 operand 가 null 포인터가 아니고, 요청된 T 의 typeid 가 operand 의 내용물과 일치하면, operand가 포함하는 값에 대한 포인터를 반환하고, 그렇지 않으면 null 포인터를 반환합니다.

예외

1-3) 요청된 T 의 typeid 가 operand 의 내용과 일치하지 않으면 std::bad_any_cast 를 throw합니다.

예제

#include <any>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
int main()
{
    // 간단한 예제
    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); // 예외 발생
    }
    catch (const std::bad_any_cast& e)
    {
        std::cout << "2) " << e.what() << '\n';
    }
    // 포인터 예제
    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";
    // 고급 예제
    a1 = std::string("hello");
    auto& ra = std::any_cast<std::string&>(a1); // 참조
    ra[1] = 'o';
    std::cout << "4) a1 is string: "
              << std::any_cast<const std::string&>(a1) << '\n'; // 상수 참조
    auto s1 = std::any_cast<std::string&&>(std::move(a1)); // 우측값 참조
    // 참고: "s1"은 이동 생성된 std::string입니다
    static_assert(std::is_same_v<decltype(s1), std::string>);
    // 참고: "a1" 내의 std::string은 유효하지만 지정되지 않은 상태로 남아 있습니다
    std::cout << "5) a1.size(): "
              << std::any_cast<std::string>(&a1)->size() // 포인터
              << '\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로 처리됨