std::type_info::operator==, std::type_info::operator!=
From cppreference.com
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まで) |
オブジェクトが同じ型を参照しているかどうかをチェックします。
|
|
(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) |