std::type_info:: operator==, std::type_info:: operator!=
From cppreference.net
C++
Utilities library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Type support
| Basic types | |||||||||||||||||||||
| Fixed width integer types (C++11) | |||||||||||||||||||||
| Fixed width floating-point types (C++23) | |||||||||||||||||||||
|
|||||||||||||||||||||
| Numeric limits | |||||||||||||||||||||
| C numeric limits interface | |||||||||||||||||||||
| Runtime type information | |||||||||||||||||||||
|
|||||||||||||||||||||
std::type_info
| Member functions | ||||
|
type_info::operator==
type_info::operator!=
(until C++20)
|
||||
|
(C++11)
|
||||
|
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
オブジェクトの参照型よりも実装定義の順序で先行するかどうかをチェックします。 つまり、参照されている型を順序付けます (公開メンバ関数) |