std::type_info::operator==, std::type_info::operator!=
cppreference.net에서
bool operator==( const type_info& rhs ) const;
|
(1) | (C++11부터 noexcept) (C++23부터 constexpr) |
bool operator!=( const type_info& rhs ) const;
|
(2) | (C++11부터 noexcept) (C++20까지) |
객체가 동일한 타입을 참조하는지 확인합니다.
|
|
(C++20부터) |
매개변수
| rhs | - | 비교할 다른 타입 정보 객체 |
반환값
true 비교 연산이 참일 경우, false 그렇지 않을 경우.
참고 사항
| 기능 테스트 매크로 | 값 | 표준 | 기능 |
|---|---|---|---|
__cpp_lib_constexpr_typeinfo
|
202106L
|
(C++23) |
std::type_info::operator==
에 대한 constexpr
|
예제
이 코드 실행
#include <iostream> #include <string> #include <typeinfo> #include <utility> class person { public: explicit person(std::string n) : name_(std::move(n)) {} virtual const std::string& name() const { return name_; } private: std::string name_; }; class employee : public person { public: employee(std::string n, std::string p) : person(std::move(n)), profession_(std::move(p)) {} const std::string& profession() const { return profession_; } private: std::string profession_; }; void print_info(const person& p) { if (typeid(person) == typeid(p)) std::cout << p.name() << " is not an employee\n"; else if (typeid(employee) == typeid(p)) { std::cout << p.name() << " is an employee "; auto& emp = dynamic_cast<const employee&>(p); std::cout << "who works in " << emp.profession() << '\n'; } } int main() { print_info(employee{"Paul","Economics"}); print_info(person{"Kate"}); #if __cpp_lib_constexpr_typeinfo if constexpr (typeid(employee) != typeid(person)) // C++23 std::cout << "class `employee` != class `person`\n"; #endif }
가능한 출력:
Paul is an employee who works in Economics Kate is not an employee class `employee` != class `person`
참고 항목
참조된 타입이 다른
type_info
객체의 참조된 타입보다 구현 정의 순서에서
앞서는지 확인합니다. 즉, 참조된 타입들을 순서화합니다 (public member function) |