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

来自cppreference.com
< cpp‎ | types‎ | type info
 
 
 
 
std::type_info
成员函数
type_info::operator==type_info::operator!=
(C++20 前)
 
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 前)

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

!= 运算符从 operator== 运算符合成

(C++20 起)

参数

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

返回值

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

注解

功能特性测试标准功能特性
__cpp_lib_constexpr_typeinfo202106L(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() << " 不是雇员\n";
    else if (typeid(employee) == typeid(p))
    {
        std::cout << p.name() << " 是雇员,";
        auto& emp = dynamic_cast<const employee&>(p);
        std::cout << "工作于 " << emp.profession() << '\n';
    }
}
 
int main()
{
    print_info(employee{"Paul","经济学"});
    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 是雇员,工作于 经济学
Kate 不是雇员
class `employee` != class `person`

参阅

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