std::type_info::operator==, std::type_info::operator!=

来自cppreference.com
< cpp‎ | types‎ | type info
 
 
工具库
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)
(C++20)
swap 与类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)
 
 
std::type_info
成员函数
type_info::operator==type_info::operator!=
(C++20 前)
 
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 对象之前,即对被指代类型排序
(公开成员函数)