理解C++运行时类型识别符: typeid

c++关键字之typeid typeid是 C++ 中用于获取运行时类型信息的操作符,主要通过返回对象来实现。可以用于判断对象的类型,尤其在多态场景中,有助于实现动态类型检查和运行时类型比较。使用时要注意多态性要求和对空指针的处理,避免意外的异常抛出。通过使用typeid,可以在运行时检查对象的类型,对于处理多态对象、调试代码以及实现更复杂的动态类型逻辑非常有用,但要注意不同编译器对type_info的实现细节可能有所不同,特别是name()方法返回的字符串表示。 阅读详情

1.  格式

typeid (type-id)

typeid (expression)

typeid 运算符允许在运行时确定对象的类型。

typeid 的结果是一个 const type_info&。该值是对 type_info 对象的引用,该对象表示 type-id 或表达式的类型,具体取决于使用哪种形式的 typeid。有关更多信息,请参阅 type_info 类。

typeid 运算符不适用于托管类型(抽象声明符或实例)。

当将 typeid 运算符应用于多态类类型的左值时,它会执行运行时检查,其中对象的真实类型无法通过提供的静态信息确定。此类情况包括:

• 对类的引用

• 指针,使用 * 解引用

• 带下标的指针 ([ ])。(将下标与指向多态类型的指针一起使用是不安全的。)

2.  用法举例

如果表达式指向基类类型,但对象实际上是从该基类派生的类型,则结果为派生类的 type_info 引用。表达式必须指向多态类型(具有virtual函数的类)。否则,结果为表达式中引用的静态类的 type_info。此外,必须解引用指针,以便使用的对象是它指向的对象。如果不解引用指针,结果将是指针的 type_info,而不是它指向的对象。例如:

C++:

// expre_typeid_Operator.cpp

// compile with: /GR /EHsc

#include <iostream>

#include <typeinfo>

class Base {

public:

   virtual void vvfunc() {}

};

class Derived : public Base {};

using namespace std;

int main() {

   Derived* pd = new Derived;

   Base* pb = pd;

   cout << typeid( pb ).name() << endl;   //prints "class Base *"

   cout << typeid( *pb ).name() << endl;   //prints "class Derived"

   cout << typeid( pd ).name() << endl;   //prints "class Derived *"

   cout << typeid( *pd ).name() << endl;   //prints "class Derived"

   delete pd;

}

如果表达式是解引用指针,并且该指针的值为零,则 typeid 会抛出 bad_typeid 异常。如果指针未指向有效对象,则会抛出 __non_rtti_object 异常。它表示尝试分析触发错误的 RTTI,因为该对象某种程度上无效。(例如,它是一个糟糕的指针,或者代码未使用 /GR 编译)。

如果表达式不是指针,也不是指向对象基类的引用,则结果为表示表达式静态类型的 type_info 引用。表达式的静态类型是指编译时已知的表达式类型。在评估表达式的静态类型时,将忽略执行语义。此外,在确定表达式的静态类型时,将尽可能忽略引用:

C++:

// expre_typeid_Operator_2.cpp

#include <typeinfo>

int main()

{

   typeid(int) == typeid(int&); // evaluates to true

}

typeid 也可以在模板中使用来确定模板参数的类型:

C++:

// expre_typeid_Operator_3.cpp

// compile with: /c

#include <typeinfo>

template < typename T >

T max( T arg1, T arg2 ) {

   cout << typeid( T ).name() << "s compared." << endl;

   return ( arg1 > arg2 ? arg1 : arg2 );

}

C++ `typeid` 运算符 阅读详情

相关推荐

【深度C++】之“typeid与type_info”

typeid与type_info。

不能自拔 4881

C++ typeid关键字详解

C++ typeid关键字详解

路过的熊的博客 6615

C++(03):获取类型信息的typeid运算符

typeid 运算符用来获取一个类型的类型信息,他的操作对象可以是表达式,也可以是数据类型: typeid( dataType ) typeid( expression ) typeid 会把获取到的类型信息保存到一个 type_info 类型的对象里面,并返回该对象的常量引用;可以通过成员函数name()来提取类型信息字符串,但C++没有规定name()返回的字符串格式,所以不同的编译器返回的格式是不一样的。 此外typeid还可以用于的判断。 #include <iostream>

风静如云的博客 932

C++ 编程基础(9)RTTI(Runtime Type Information)机制

C++中的RTTI机制提供了一种在运行时查询和操作类型信息的强大工具。然而,它并不是万能的,也有其限制和潜在的问题。开发者在使用RTTI时需要权衡其利弊,并根据具体的应用场景和需求来做出决策。在可能的情况下,应优先考虑使用C++的其他特性(如模板、多态等)来实现类型安全和灵活性的需求。

个人技术博客 3584

STM32硬件SPI驱动W5500以太网模块全流程(附避坑指南)

本文详细介绍了STM32硬件SPI驱动W5500以太网模块的全流程,包括硬件架构设计、SPI接口选型、官方驱动移植、网络协议栈配置与优化等关键步骤。通过实战案例和性能对比数据,帮助开发者快速实现稳定高效的网络连接,特别提供了常见问题排查指南和性能调优技巧。

weixin_29194693的博客 275

我从华为身上学到的项目管理经验 -- 需求篇

记录这三年,关于项目管理上的一些心得体会 – 需求篇对于需求,我们可以根据不同的角色、理解拆分成三个过程:简单来说就是:需求分析原始需求、 需求拆分为系统需求、 需求实现为功能需求**需求分析**: 将客户需求 输出成 需求描述。 需求经理需要把 需求 转换成 客户能够接受的 初始需求 IR(Initial Requirement) 对于用户来说,我只管提 我的原始需求是

minminzhe520的博客 3万+

C++中的typeid

typeid是 C++ 中的运算符,用于获取表达式或类型的运行时类型信息。它返回一个std::type_info对象,该对象包含有关类型的信息,例如类型的名称。

m0_61629312的博客 2031

Apache Paimon快照管理实战:如何避免Flink作业中的反压问题?

本文深入探讨了如何通过优化Apache Paimon的快照管理机制来避免Flink作业中的反压问题。详细解析了同步与异步快照过期模式的适用场景及配置建议,并提供了Checkpoint策略与状态后端的协同优化方案,帮助提升实时数据处理的性能和稳定性。

i1j2k的博客 178

C++ typeid详解

C++为我们提供了一种可以判断变量类型的关键字,即typeid,它的参数和sizeof一样,可以是一个变量,或者一种类型。typeid的返回值是type_info类,而且返回的是一个左值。type_info类禁用了拷贝构造函数,因此我们必须要用引用或指针来存储结果,如: const type_info& type1=typeid(int); const type_info* type2=&typeid(int); name() 作用:返回描述变量类型的字符串(注意:是类型全名)。 基本用法

[PE]经典八炮的博客 9233

16、保障Azure应用安全:密钥管理与身份认证

本文深入探讨了保障Azure应用安全的关键措施,包括使用网络安全工具(如Application Gateway和Azure Front Door)防范攻击,解决传统密钥和机密存储方式的安全隐患,以及通过Azure Key Vault实现敏感信息的安全管理。同时,介绍了使用托管标识实现Azure资源间安全访问的方法,并结合实际操作步骤展示了如何配置Key Vault、设置访问策略、存储机密以及授予Web应用对SQL Server的访问权限。最后,对不同安全措施进行了比较,并提出了在开发、测试及生产环境中的综合

rock5的博客 78

手把手教你学PCIE--系统内存管理:GART(Graphics Address Remapping Table)的典型用途详解

GART(图形地址重映射表)是GPU的核心组件,主要用于地址映射转换。其典型用途分为物理模式和虚拟模式两类:在物理模式下,GART将GPU虚拟地址映射到分散的物理内存,支持DMA连续访问非连续内存块,适用于GPU渲染纹理采样和AI推理数据搬运等场景;在虚拟模式下,GART配合IOMMU实现多级映射,将GPU虚拟地址转换为虚拟机物理地址再映射到宿主机物理地址,确保多租户隔离,应用于云服务器GPU共享和容器化AI训练等虚拟化环境。两种模式分别优化了高性能计算场景和虚拟化场景的需求。

MHD0815的博客 371

c++关键字typeid

typeid是c++的一个关键字,typeid操作符的返回结果是标准库类型type_info对象的引用。 但是,C++标准并没有明确定义type_info,其具体实现依赖于各个编译器。标准只规定了typeid操作符必需实现如下四种操作: 操作 说明 t1 == t2 如果两个对象t1和t2类型相同,则返回true;否则返回false t1 != t2 如果两个对象t1和t2类型不同,则返回true;否则返回false t.name() 返回类型的C-style字符串。由编..

吴尼玛cs 636

激光打标轴坐标计算分析

‌:基于坐标差的平方和开方运算,勾股定理将几何关系转化为代数计算,从而实现了从坐标到距离的精确转换‌12。直角三角形的应用从上图可以看到A,B,P三个点连起来就是一个直角三角形了。用勾股定理计算距离 C#有相关的方法直接传参数就可以了。很方便。

StevenChen的博客 318

C++11新特性之typeid关键字使用

typeid运算符用来获取一个表达式的类型信息。类型信息对于编程语言非常重要,它描述了数据的各种属性:对于基本类型(int、float 等C++内置类型)的数据,类型信息所包含的内容比较简单,主要是指数据的类型。对于类类型的数据(也就是对象),类型信息是指对象所属的类、所包含的成员、所在的继承关系等。typeid运算符返回一个std::type_info对象,表示表达式的实际类型。

悟空爱编程 1385

UG NX二次开发(C#)-VS2022配置NX二次开发模板不能正常显示的问题

随着VS2022的发布,使用VS2022进行UG NX二次开发的人员也会越来越多,但是由于VS2022和以前的VS版本采用代码结构不同,而UG NX的二次开发编程模板还没有适应于VS2022的模板配置,所以不能正常的创建一个完整的工程。本文采用曲线救国的方式来实现VS2022下的UG NX二次开发。如果有读者能很好的解决模板配置,不吝赐教。

GimiGimmy 4283

第五天 Labview数据记录(5.4 EXCEL文件读写)

Excel 文件读写在数据处理、自动化办公、数据分析等领域具有重要的意义。以下是 Excel 文件读写的主要应用场景和意义:1. 数据管理和整理;2. 自动化办公;3. 数据分析和可视化;4. 系统集成;5. 报表生成;6. 教育和培训;7. 实际应用场景。Excel 文件读写的意义在于提高数据处理的效率、减少人工操作、支持自动化办公、促进数据分析和可视化,以及实现系统之间的数据交互。无论是企业、组织还是个人,都可以通过 Excel 文件读写实现数据的高效管理和利用。

weixin_38637405的博客 1268

C++之typeid的介绍

C++之typeid的介绍

techenliu的博客 637

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

c++的关键字typeid

文章目录一、什么typeid?二、怎么用typeid 一、什么typeid? 二、怎么用typeid 注意:typeid的定义和声明是在typeinfo中,所以预编译头文件的时候需要包含#include。 #include<iostream> #include<typeinfo> //必须要包含该头文件 using namespace std; int main() { int a = 0; double b = 2.0; cout <&lt

weixin_44355245的博客 399

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

C++通过typeid获取类名或者类型名

typeid是C++的一个运算符 typeid(int).name()     输出const char*的类型名字,需要支持RTTI char b[5]={'a', 'b', 'c', 'd', 'e'}; int sum1=Total(b, b+4);  template  R Total(const T* beg, const T* end)  {

lnwaycool的专栏 1万+

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

C++中typeid的使用

C++中typeid的使用

网络资源是无限的 1万+

C++ 类型(typeid、RTTI、decltype等)

1,typeid操作符 用法和sizeof很像,既可以用于变量,也可以用于类型,作用是指出他们的类型。 #include<iostream> #include <c++/memory> using namespace std; class A { }; int main() { cout<<typeid(12).name()<<" "; cout<<typeid(int).name()<<" "; ...

nameofcsdn的博客 2472

typeid(T).name() 方法在 linux 下通过 g++ 编译得不到变量正确的类型

说实话,我不是 c++ 程序员,之前虽然出于个人兴趣研究过 c++,也跟风看过《c++ primer》。 但是要说水平,我估计还没入门吧。 要不是之前苦学过一段时间的 c,估计连基本的语法也一知半解了。 最近在研究 nodejs,当然不是研究 nodejs 常用的 api 怎么用,如果只是仅仅止步于此的话,根本用不着接触到 c++ 了。 我们知道,nodejs 是用 c++ 写的,而且 node...

纯爱枫若情的博客 2348

从C向C++9——typeid和RTTI

了解typeid和RTTI

墨城烟柳ベ旧人殇的博客 1559

C++20学习笔记——部分多态

在基类中声明为virtual的函数在从基类(直接或间接)派生的所有类中都是虚函数。在派生类中,无论是否把函数指定为virtual,它都是虚函数。

XXTongC的博客 210

C++ 中的 typeid 运算符和示例

typeid是C++ 中的运算符。

1007
上一篇: 理解C++编译时类型转换符:static_cast
下一篇: C++编程语言:抽象机制:第23章——模板(Bjarne Stroustrup)
ComputerInBook
博客等级 码龄19年 1168粉丝 465原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址