在C ++中动态声明数据类型 [英] Declaring a data type dynamically in C++

查看:173
本文介绍了在C ++中动态声明数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够执行以下操作:

I want to be able to do the following:

我有一个包含数据类型的字符串数组:

I have an array of strings that contain data types:

string DataTypeValues[20] = {"char", "unsigned char", "short", "int"};

然后,我想在运行时创建一种数据类型的变量。我不会在编译时知道正确的数据类型。

Then later, I would like to create a variable of one of the data types at runtime. I won't know at compile time what the correct data type should be.

因此,例如,如果在运行时我确定变量x需要为int类型:

So for example, if at runtime I determined a variable x needed to be of type int:

DataTypeValues[3] x = 100;

显然这行不通,那么我该怎么做?

Obviously this won't work, so how could I do something like this?

推荐答案

简单的答案是您不能-在C ++中需要在编译时知道类型。您可以使用boost :: any或union来执行类似的操作,但是效果并不理想。

The simple answer is that you can't - types need to be known at compile time in C++. You can do something like it using things like boost::any or unions, but it won't be pretty.

这篇关于在C ++中动态声明数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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