名前空間
変種
操作

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

From cppreference.com
< cpp‎ | types‎ | type info
 
 
ユーティリティライブラリ
言語サポート
型のサポート (基本型、RTTI)
ライブラリ機能検査マクロ (C++20)
プログラムユーティリティ
可変引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)  
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
 
 
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_typeinfo 202106L (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() << " 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()
{
    print_info(employee{"Paul","Economics"});
    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 is an employee who works in Economics
Kate is not an employee
class `employee` != class `person`

[編集] 関連項目

参照している型が、別のtype_infoの参照している型よりも前に来るかどうかをチェックします。
実装定義順序におけるオブジェクト、つまり参照している型を順序付けます。
(public member function) [編集]
English 日本語 中文(简体) 中文(繁體)