CppDS.com

C++ 98 11 14 17 20 手册

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

来自cppreference.com
< cpp‎ | types‎ | type info
 
 
工具库
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)
swap 与类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等字符串转换
(C++17)
(C++17)
 
类型支持
基本类型
基础类型
定宽整数类型 (C++11)
数值极限
C 数值极限接口
运行时类型信息
类型特性
类型类别
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
类型属性
(C++11)
(C++11)
(C++14)
(C++11)
(C++11)(C++20 前)
(C++11)(C++20 中弃用)
(C++11)
类型特性常量
元函数
(C++17)
常量求值语境
受支持操作
关系与属性查询
类型修改
(C++11)(C++11)(C++11)
类型变换
(C++11)
(C++11)
(C++17)
(C++11)(C++20 前)(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 起)
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 对象之前,即对被指代类型排序
(公开成员函数)
关闭