C ++:是否可以在执行时设置空指针,变量对象或任意对象的类型? [英] C++: Is it posible to set the type of a void-pointer, variant-object or any-object in execution time?

查看:69
本文介绍了C ++:是否可以在执行时设置空指针,变量对象或任意对象的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

空指针,变量对象和任意对象之所以令人惊叹,是因为它们可以在同一个变量中存储许多不同的类型.但是我有一个问题,我需要在执行时指定它们的类型(创建和/或取消引用它们),有可能吗?

Void-pointer, variant-objects and any-objects are amazing because they can store many different types in the same variable. But I have a problem with them, I need to specify their type (creating and/or de-referencing them) in the execution time, is it possible?

例如,据我所知,要创建和取消引用它们,我必须这样做:

To be more clear, for example, as far I know, to create and de-reference them I have to do this:

void* ptr = new int(8);
variant<int, float> var = 8;
any a = 8;
...
cout << *(int*)ptr;
cout << get<int>(var);
cout << any_cast<int>(a);

如您所见,在所有情况下,必须将类型用代码编写".(编程时间?).如果可以在执行时间确定该类型,那将是非常好的.让我梦见...例如,如果我们可以存储类型",作为对象,我们可以这样做:

As you can see, in all cases the type must be "written in the code" (programming-time?). It would be excellent if that type could be determinate in the execution time. Let me dream... if, for example, we could "store a type" as an object, we could do this:

TYPE mi_tipo;
...
mi_tipo = int;   // or float, or char or any other...
...
void* ptr = new mi_tipo();
cout << *(mi_tipo*)ptr;

像这样的事情有可能吗?如果没有,您将如何做?我正在尝试模拟编译器执行的操作,因此我需要一个可以存储任何类型的变量的结构,因此需要在执行时取消引用它们的有效方法.

Something like this is possible? If not, how would you do this? I'm trying to do simulate a compiler perform, so I need an structure which can store any type of variables, and so I need an efficient way of de-reference them in execution time.

推荐答案

C ++是一种静态类型的语言.任何表达式的类型都必须在编译时知道.尽管编译时代码可以执行有限形式的类型计算,甚至可以在某种程度上进行类型生成,但所有这些在编译时仅存在 .

C++ is a statically typed language. The type of any expression must be known at compile-time. While compile-time code can do limited forms of type computation, and even type generation to a degree, all of that exists only at compile-time.

一旦到达运行时,一切都必须知道.存在通过基类和 virtual 函数进行的动态多态性,但是在创建实际对象时,您必须知道它是什么类型.有一些技术可以动态确定要实例化的多态派生类,但最终它们最终都归结为一堆条件语句和一组硬编码(即使通过模板生成的)类型集.

Once you reach the runtime, everything has to be known. Dynamic polymorphism through base classes and virtual functions exist, but at the point the actual object is created, you have to know what type it is. There are techniques which can allow dynamically determining which polymorphic derived class to instantiate, but they all ultimately boil down to a bunch of conditional statements and a hard-coded (even if generated through templates) set of types.

这篇关于C ++:是否可以在执行时设置空指针,变量对象或任意对象的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆