【发布时间】:2011-08-22 16:23:52
【问题描述】:
如果我有以下假设类:
namespace System
{
template <class T>
class Container
{
public:
Container() { }
~Container() { }
}
}
如果我用不同的 T 实例化两个容器,比如说:
Container<int> a;
Container<string> b;
我想用指向 a 和 b 的指针创建向量。由于 a 和 b 是不同的类型,通常这是不可能的。但是,如果我做了类似的事情:
std::stack<void*> _collection;
void *p = reinterpret_cast<void*>(&a);
void *q = reinterpret_cast<void*>(&b);
_collection.push(a);
_collection.push(b);
然后,我可以像这样从 _collection 中获取 a 和 b:
Container<string> b = *reinterpret_cast<Container<string>*>(_collection.pop());
Container<int> a = *reinterpret_cast<Container<int>*>(_collection.pop());
我的问题是,这是存储不相关类型集合的最佳方式吗?这也是从向量中存储和检索指针的首选方式(重新解释转换)吗?我环顾四周,发现 boost 有更好的方法来解决这个问题,Boost::Any,但由于这是一个学习项目,我想自己做(而且我一直很好奇找到一个很好的理由正确使用 reinterpret_cast)。
【问题讨论】:
-
我认为
reinterpret_cast从来没有(或几乎从来没有)有充分的理由,整个项目感觉就像一股巨大的气味。 :-(
标签: c++ generics containers