std::type_info:: operator==, std::type_info:: operator!=
From cppreference.net
C++
Utilities library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Type support
| Basic types | |||||||||||||||||||||
| Fixed width integer types (C++11) | |||||||||||||||||||||
| Fixed width floating-point types (C++23) | |||||||||||||||||||||
|
|||||||||||||||||||||
| Numeric limits | |||||||||||||||||||||
| C numeric limits interface | |||||||||||||||||||||
| Runtime type information | |||||||||||||||||||||
|
|||||||||||||||||||||
std::type_info
| Member functions | ||||
|
type_info::operator==
type_info::operator!=
(until C++20)
|
||||
|
(C++11)
|
||||
|
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 前) |
检查对象是否引用相同类型。
|
|
(since C++20) |
目录 |
参数
| rhs | - | 要与之比较的另一个类型信息对象 |
返回值
true 表示比较操作成立, false 表示不成立。
注释
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__cpp_lib_constexpr_typeinfo
|
202106L
|
(C++23) |
std::type_info::operator==
的常量表达式支持
|
示例
运行此代码
#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
对象所引用的类型,即对引用类型进行排序 (公开成员函数) |