std::type_info::operator==, std::type_info::operator!=
来自cppreference.com
bool operator==( const type_info& rhs ) const; |
(C++11 前) | |
bool operator==( const type_info& rhs ) const noexcept; |
(C++11 起) (C++23 前) |
|
constexpr bool operator==( const type_info& rhs ) const noexcept; |
(C++23 起) | |
bool operator!=( const type_info& rhs ) const; |
(C++11 前) | |
bool operator!=( const type_info& rhs ) const noexcept; |
(C++11 起) (C++20 前) |
|
检查对象是否指代相同类型。
|
(C++20 起) |
参数
rhs | - | 要比较的另一个类型信息对象 |
返回值
若比较关系成立则为 true ,否则为 false
示例
运行此代码
#include <iostream> #include <typeinfo> #include <string> #include <utility> class person { public: 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 somefunc(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() { somefunc(employee{"Paul","Economics"}); somefunc(person{"Kate"}); # if defined(__cpp_lib_constexpr_typeinfo) // C++23 if constexpr (typeid(employee) != typeid(person)) { std::cout << "class `employee` != class `person`\n"; } # endif }
输出:
Paul is an employee who works in Economics Kate is not an employee
参阅
检查在实现定义的顺序中,被指代类型是否在另一个 type_info 对象之前,即对被指代类型排序 (公开成员函数) |