Home > Backend Development > C++ > body text

Usage of typeid in c++

下次还敢
Release: 2024-05-01 11:42:17
Original
745 people have browsed it

The typeid operator obtains the static type information of the object and returns a type_info object, which contains type name, size, alignment, base class, modifiers and other information. Object information can be accessed through methods such as name(), before(), and base().

Usage of typeid in c++

Usage of typeid in C

The typeid operator is a C keyword used to obtain the static properties of an object Type information. It returns a type_info object that contains various information about the object type.

Usage:

The typeid operator is followed by an expression that represents the expression whose type information is to be obtained. The expression can be:

  • Variable
  • Expression
  • Function return type
  • Type alias

Syntax:

<code class="cpp">typeid(expression) // 其中 expression 是要获取其类型信息的表达式</code>
Copy after login

Return value:

The typeid operator returns a type_info object containing the following information about the object type:

  • Type name
  • Type size
  • Type alignment
  • Type derivation information
  • Type basic information
  • Type modifier information
  • Type modification information

You can access the information in the type_info object through the following methods:

  • name(): Return the type name
  • before() and after(): Get the base class from the derived class and get the derived class from the base class
  • base(): Return the direct base class
  • grow() and shrink( ): Modify the array size in the type name
  • modifier(): Return type modifier

Example:

<code class="cpp">int main() {
  int x;
  std::string s;
  std::cout << typeid(x).name() << std::endl; // 输出:int
  std::cout << typeid(s).name() << std::endl; // 输出:std::__cxx11::basic_string<char>
  return 0;
}</code>
Copy after login

Note: The

  • #typeid operator can only be used with static type information. It cannot be used to obtain runtime type information for an object.
  • The results of the typeid operator may vary between compilers and platforms.
  • The typeid operator has little overhead, but using it frequently may degrade performance.

The above is the detailed content of Usage of typeid in c++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
c++
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template