std::type_info::operator==, std::type_info::operator!=
来自 cppreference.com
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。
[编辑] 注释
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__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 的引用类型之前对象在实现定义的顺序中,即对引用的类型进行排序 (公共成员函数) |