乐闻世界logo
搜索文章和话题

' typeid ' versus ' typeof ' in C++

1个答案

1

In C++, typeid and typeof (or in some cases, decltype) are keywords used to obtain type information, but they differ in usage and purpose.

1. typeid

typeid is a keyword provided by the C++ standard library, used to determine the type of an object or expression at runtime. It is closely related to Runtime Type Information (RTTI). Primarily used in polymorphic contexts, it provides a reference to a type_info object, which contains information about the type.

Example:

cpp
#include <iostream> #include <typeinfo> class Base { public: virtual void print() { std::cout << "Base class" << std::endl; } }; class Derived : public Base { public: void print() override { std::cout << "Derived class" << std::endl; } }; int main() { Base* b = new Derived(); std::cout << "b is: " << typeid(*b).name() << std::endl; // Outputs the derived class name delete b; return 0; }

In this example, even though b is a pointer of type Base, typeid detects that b points to an instance of Derived and returns the type information for Derived.

2. decltype

decltype is a keyword introduced in C++11, used for deducing the type of an expression at compile time. It does not involve runtime type information and is fully resolved at compile time.

Example:

cpp
#include <iostream> int main() { int x = 5; decltype(x) y = 10; // y is deduced to be of type int std::cout << "y is: " << y << std::endl; return 0; }

In this example, decltype(x) is used to infer the type of x, and a variable y of the same type is declared.

Notes

  • typeid requires runtime support, especially when dealing with polymorphic types.
  • decltype is part of the C++11 standard, whereas typeof is a non-standard extension in some compilers, making decltype more portable and standardized.

In summary, typeid is primarily used for obtaining runtime type information, while decltype is used for inferring the type of variables or expressions at compile time.

2024年6月29日 12:07 回复

你的答案