注意:我知道之前在 SO 上也有人问过类似的问题,但我觉得它们没有帮助或很清楚.
Note: I know similar questions to this have been asked on SO before, but I did not find them helpful or very clear.
第二点:对于这个项目/作业的范围,我试图避免使用第三方库,例如 Boost.
Second note: For the scope of this project/assignment, I'm trying to avoid third party libraries, such as Boost.
我想看看是否有一种方法可以让单个向量在其每个索引中包含多种类型.例如,假设我有以下代码示例:
I am trying to see if there is a way I can have a single vector hold multiple types, in each of its indices. For example, say I have the following code sample:
vector<something magical to hold various types> vec;
int x = 3;
string hi = "Hello World";
MyStruct s = {3, "Hi", 4.01};
vec.push_back(x);
vec.push_back(hi);
vec.push_back(s);
我听说 vector<void*>
可以工作,但是它在内存分配方面变得棘手,然后总是有可能附近内存中的某些部分可能会被无意中覆盖,如果插入到某个索引中的值比预期的要大.
I've heard vector<void*>
could work, but then it gets tricky with memory allocation and then there is always the possibility that certain portions in nearby memory could be unintentionally overridden if a value inserted into a certain index is larger than expected.
在我的实际应用中,我知道什么可能类型可以插入到一个向量中,但是这些类型并不都派生自同一个超类,并且不能保证所有这些类型将被推到向量上或以什么顺序.
In my actual application, I know what possible types may be inserted into a vector, but these types do not all derive from the same super class, and there is no guarantee that all of these types will be pushed onto the vector or in what order.
有什么方法可以安全实现我在代码示例中演示的目标?
Is there a way that I can safely accomplish the objective I demonstrated in my code sample?
感谢您的宝贵时间.
为了做到这一点,您肯定需要一个包装类来以某种方式从向量中隐藏对象的类型信息.
In order to do that, you'll definitely need a wrapper class to somehow conceal the type information of your objects from the vector.
当您之前将 Type-B 存储到 Type-A 中时,让此类在尝试取回 Type-A 时抛出异常可能也不错.
It's probably also good to have this class throw an exception when you try to get Type-A back when you have previously stored a Type-B into it.
这是我的一个项目中 Holder 类的一部分.你或许可以从这里开始.
Here is part of the Holder class from one of my projects. You can probably start from here.
注意:由于使用了不受限制的联合,这仅适用于 C++11. 可以在此处找到有关此的更多信息:C++11 中提出的无限制联合是什么?
Note: due to the use of unrestricted unions, this only works in C++11. More information about this can be found here: What are Unrestricted Unions proposed in C++11?
class Holder {
public:
enum Type {
BOOL,
INT,
STRING,
// Other types you want to store into vector.
};
template<typename T>
Holder (Type type, T val);
~Holder () {
// You want to properly destroy
// union members below that have non-trivial constructors
}
operator bool () const {
if (type_ != BOOL) {
throw SomeException();
}
return impl_.bool_;
}
// Do the same for other operators
// Or maybe use templates?
private:
union Impl {
bool bool_;
int int_;
string string_;
Impl() { new(&string_) string; }
} impl_;
Type type_;
// Other stuff.
};
这篇关于C++ 将多种类型推送到向量上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!