C++ 参考手册

位置:首页 > C++ 参考手册 >类型支持(基本类型、RTTI、类型特性) >std::type_info > std::type_info::operator==, std::type_info::operator!=

bool operator==( const type_info& rhs ) const;
(C++11 前)
bool operator==( const type_info& rhs ) const noexcept;
(C++11 起)
bool operator!=( const type_info& rhs ) const;
(C++11 前)
bool operator!=( const type_info& rhs ) const noexcept;
(C++11 起)
(C++20 前)

检查对象是否指代相同类型。

参数

rhs - 要比较的另一个类型信息对象

返回值

若比较关系成立则为 true ,否则为 false

示例

#include <iostream>
#include <typeinfo>
#include <string>
#include <utility>
 
class person
{
  public:
 
   person(std::string&& n) : _name(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(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()
{
   employee paul("Paul","Economics");
   somefunc(paul);
}

输出:

Paul is an employee who works in Economics

参阅

检查在实现定义的顺序中,被指代类型是否在另一个 type_info 对象之前,即对被指代类型排序
(公开成员函数)