Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

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

      From cppreference.com
      <cpp‎ |types‎ |type info
       
       
      Utilities library
       
       
      std::type_info
      Member functions
      type_info::operator==type_info::operator!=
      (until C++20)
       
      bool operator==(const type_info& rhs)const;
      (1)(noexcept since C++11)
      (constexpr since C++23)
      bool operator!=(const type_info& rhs)const;
      (2)(noexcept since C++11)
      (until C++20)

      Checks if the objects refer to the same types.

      The!= operator issynthesized fromoperator==.

      (since C++20)

      Contents

      [edit]Parameters

      rhs - another type information object to compare to

      [edit]Return value

      true if the comparison operation holds true,false otherwise.

      [edit]Notes

      Feature-test macroValueStdFeature
      __cpp_lib_constexpr_typeinfo202106L(C++23)Constexpr forstd::type_info::operator==

      [edit]Example

      Run this code
      #include <iostream>#include <string>#include <typeinfo>#include <utility> class person{public:explicit person(std::string n): name_(std::move(n)){}virtualconststd::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)){} conststd::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";elseif(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_typeinfoifconstexpr(typeid(employee)!=typeid(person))// C++23std::cout<<"class `employee` != class `person`\n";#endif}

      Possible output:

      Paul is an employee who works in EconomicsKate is not an employeeclass `employee` != class `person`

      [edit]See also

      checks whether the referred type precedes referred type of anothertype_info
      object in the implementation defined order, i.e. orders the referred types
      (public member function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/types/type_info/operator_cmp&oldid=173460"

      [8]ページ先頭

      ©2009-2025 Movatter.jp