std::any:: type
From cppreference.net
C++
Utilities library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
const
std::
type_info
&
type
(
)
const
noexcept
;
|
(C++17부터) | |
포함된 타입을 조회합니다.
반환값
인스턴스가 비어 있지 않은 경우 포함된 값의 typeid , 그렇지 않으면 typeid ( void ) 입니다.
예제
이 예제는 컴파일 타임과 런타임에 새로운 방문자를 등록할 수 있는 기능을 가진
std::any
방문자 관용구를 보여줍니다.
이 코드 실행
#include <any> #include <functional> #include <iomanip> #include <iostream> #include <type_traits> #include <typeindex> #include <typeinfo> #include <unordered_map> #include <vector> template<class T, class F> inline std::pair<const std::type_index, std::function<void(const std::any&)>> to_any_visitor(const F& f) { return { std::type_index(typeid(T)), [g = f](std::any const& a) { if constexpr (std::is_void_v **변경사항 없음** - HTML 태그와 속성은 번역하지 않음 - ``, `` 태그 내 텍스트는 C++ 전문 용어이므로 번역하지 않음 - `std::is_void_v`는 C++ 표준 라이브러리 타입 특성으로 원문 유지<T>) g(); else g(std::any_cast<T const&>(a)); } }; } static std::unordered_map<std::type_index, std::function<void(const std::any&)>> any_visitor { to_any_visitor<void>([] { std::cout << "{}"; }), to_any_visitor<int>([](int x) { std::cout << x; }), to_any_visitor<unsigned>([](unsigned x) { std::cout << x; }), to_any_visitor<float>([](float x) { std::cout << x; }), to_any_visitor<double>([](double x) { std::cout << x; }), to_any_visitor<char const*>([](char const* s) { std::cout << std::quoted(s); }), // ... 사용자 정의 타입에 대한 핸들러를 더 추가하세요 ... }; inline void process(const std::any& a) { if (const auto it = any_visitor.find(std::type_index(a.type())); it != any_visitor.cend()) it->second(a); else std::cout << "등록되지 않은 타입 " << std::quoted(a.type().name()); } template<class T, class F> inline void register_any_visitor(const F& f) { std::cout << "유형에 대한 방문자 등록" << std::quoted(typeid(T).name()) << '\n'; any_visitor.insert(to_any_visitor<T>(f)); } int main() { std::vector<std::any> va{{}, 42, 123u, 3.14159f, 2.71828, "C++17"}; for (int n{}; const std::any& a : va) { std::cout << (n++ ? ", " : "["); process(a); } std::cout << "]\n"; process(std::any(0xFULL)); //< 등록되지 않은 타입 "y" (unsigned long long) std::cout << '\n'; register_any_visitor<unsigned long long>([](auto x) { std::cout << std::hex << std::showbase << x; }); process(std::any(0xFULL)); //< OK: 0xf std::cout << '\n'; }
가능한 출력:
[{}, 42, 123, 3.14159, 2.71828, "C++17"]
등록되지 않은 타입 "y"
타입 "y"에 대한 방문자 등록
0xf
참고 항목
|
(C++11)
|
type_info
객체를 감싸는 래퍼로, 연관 컨테이너와 비순차 연관 컨테이너에서 인덱스로 사용 가능
(클래스) |