std::type_info::operator==, std::type_info::operator!=
| (1) | ||
bool operator==( const type_info& rhs ) const; |
(до C++11) | |
bool operator==( const type_info& rhs ) const noexcept; |
(с C++11) (до C++23) |
|
constexpr bool operator==( const type_info& rhs ) const noexcept; |
(с C++23) | |
| (2) | ||
bool operator!=( const type_info& rhs ) const; |
(до C++11) | |
bool operator!=( const type_info& rhs ) const noexcept; |
(с C++11) (до C++20) |
Проверяет, ссылаются ли объекты на один и тот же тип.
|
Оператор |
(с C++20) |
Параметры
| rhs | - | другой объект типа информации о типе для сравнения |
Возвращаемое значение
true в случае истинности оператора сравнения, false в противном случае.
Примечания
| Макрокоманда проверки наличия функции | Значение | Стандарт | Функция |
|---|---|---|---|
__cpp_lib_constexpr_typeinfo |
202106L | (C++23) | Константное выражение для std::type_info::operator== |
Пример
#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, объекта в порядке, определённом реализацией, т. е. упорядочивает указанные типы (публичный член-функция) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/types/type_info/operator_cmp