And*_*rew 4 c++ templates types store dynamic
我知道c ++模板,它允许你为多种类型编写代码,但是如果我想动态存储和访问类型呢?为什么在c ++中这么难做?
我非常喜欢不是必须做这样的事情:
enum SupportedTypes
{
IntType,
FloatType,
StringType
}
template <typename T>
class ClassThing
{
public:
T Value;
SupportedTypes Type;
}
...
//Not sure if you could even access thing->Type, but regardless, you get the idea...
switch (thing->Type)
{
case IntType:
DoSomething(((ClassThing<int>*)thing)->T);
break;
case FloatType:
DoSomething(((ClassThing<float>*)thing)->T);
break;
case StringType:
DoSomething(((ClassThing<string>*)thing)->T);
break;
}
Run Code Online (Sandbox Code Playgroud)
为什么c ++不支持这样的东西:
int whatIsThis = 5;
type t = typeid(whatIsThis); //typeid exists, but you can't do...:
t anotherInt = 5;
Run Code Online (Sandbox Code Playgroud)
?
我有另一个问题,我对收到一个好的答案更乐观:如果你选择模板化路线,如果你将它存储在一个集合中,有没有办法维护这个类型?例如:
vector<ClassThing> things;
Run Code Online (Sandbox Code Playgroud)
(顺便提一下,这将给出"类模板的参数列表......缺失"错误.)我的猜测是,不,这是不可能的,因为以上是不可能的.
谢谢!
如何在c ++中动态存储和访问类型?
有很多选择可供选择:
使用运行时多态,你有一个基类,可以为每个支持的类型提供一些通用功能和派生类; 你经常要做出一些关于你的接口应该"胖"的选择(提供只对派生类型的子集有意义的基类函数),而不是迫使客户端dynamic_cast<>用来恢复/开启运行时类型
使用一个有区别的联合(基本上,类型识别enum/ int与支持类型的联合) - boost::variant<>是一个很好的选择
在创建/存储值捕获时,您必须知道它的类型 - 您可以记录其typeinfo和地址,然后在访问变量后,您可以使用typeinfo来测试对象是否属于特定类型 - 尝试每种支持的类型直到找到匹配 - 这boost::any<>是一个很好的选择
为什么c ++不支持这样的东西:
int whatIsThis = 5;
type t = typeid(whatIsThis); //typeid exists, but you can't do...:
t anotherInt = 5;?
Run Code Online (Sandbox Code Playgroud)
它确实:
int whatIsThis = 5;
typedef decltype(whatIsThis) t;
t anotherInt = 5;
Run Code Online (Sandbox Code Playgroud)
对于运行时多态性,您可能实际上想要读取工厂(它创建了许多类型的对象之一 - 所有这些都是从某个基本接口派生的 - 给定一些运行时输入),以及克隆函数(它们创建未知运行时变量的副本)类型).
如果你选择模板化路线,如果你将它一般存储在一个集合中,是否有任何方法可以维护该类型:( 顺便说一下,
vector<ClassThing> things;这会产生"argument list for class template ... is missing"错误.)
你不能在没有实例化的情况下从模板中创建一个单独的对象,所以没有办法让整个vector也没有.一种合理的方法是从基类派生模板并将[智能]指针存储到基类中vector.
| 归档时间: |
|
| 查看次数: |
1475 次 |
| 最近记录: |