在容器中存储不同类型 [英] Storing different types in container

查看:122
本文介绍了在容器中存储不同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将不同类型的对象存储在集合中?

例如:


struct S1 {/*...*/};

struct S2 {/*...*/};

struct Sn {/*...*/};


模板< typename T> class X

{

public:

T data;

X(){}

// ...

};


// ...

X< S1> x1;

X< S2> x2;

X< Sn> xn;


这些对象可以存储在同一个集合类中(例如在矢量或地图中)吗?

How can objects of different types be stored in a collection?
For example:

struct S1 { /*...*/ };
struct S2 { /*...*/ };
struct Sn { /*...*/ };

template<typename T> class X
{
public:
T data;
X() {}
//...
};

//...
X<S1> x1;
X<S2> x2;
X<Sn> xn;

Can these objects be stored in the same collection class (for example in a vector or map)?

推荐答案


这些对象可以存储在同一个集合类中(例如在

Can these objects be stored in the same collection class (for example in a



向量中地图)?


否则除非你试图使用危险的矢量< void *> ;.


ben


vector or map)?

No unless you try to use dangerous vector<void*>.

ben


ben写道:
这些对象可以存储在同一个集合类中(对于矢量或地图中的
示例)吗?
除非你试图使用危险的矢量< void *> ;.
Can these objects be stored in the same collection class (for
example in a vector or map)?
No unless you try to use dangerous vector<void*>.




或诱人的矢量< boost :: any> ;-)

ben



Or the alluring vector<boost::any> ;-)
ben




Jonathan



Jonathan


tuvok写道:
如何将不同类型的对象存储在集合中?
例如:

struct S1 {/*...*/};
struct S2 {/*...*/};
struct Sn {/*...*/};

模板< typename T> X级
{
公开:
T数据;
X(){}
// ...
};

// ...
X< S1> x1;
X< S2> x2;
X< Sn> xn;

这些对象可以存储在同一个集合类中(例如在矢量或地图中)吗?
How can objects of different types be stored in a collection?
For example:

struct S1 { /*...*/ };
struct S2 { /*...*/ };
struct Sn { /*...*/ };

template<typename T> class X
{
public:
T data;
X() {}
//...
};

//...
X<S1> x1;
X<S2> x2;
X<Sn> xn;

Can these objects be stored in the same collection class (for example in a vector or map)?




如果它们都来自相同的基类(例如圆形,矩形,

三角形都来自形状),那么你可以将它们存储为基类的

对象(例如''shape'')。否则 - 没有。


问候,

拉里



IF they all derive from the same base class (e.g. circle, rectangle,
triangle all derive from shape), then you can store them as
objects of the base class (e.g. as ''shape''). Otherwise - no.

Regards,
Larry


这篇关于在容器中存储不同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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