Sho*_*ort 1 c++ generics containers
如果我有以下假设课程:
namespace System
{
template <class T>
class Container
{
public:
Container() { }
~Container() { }
}
}
Run Code Online (Sandbox Code Playgroud)
如果我实例化两个具有不同T的容器,请说:
Container<int> a;
Container<string> b;
Run Code Online (Sandbox Code Playgroud)
我想用指向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);
Run Code Online (Sandbox Code Playgroud)
然后,我可以从_collection返回a和b,如下所示:
Container<string> b = *reinterpret_cast<Container<string>*>(_collection.pop());
Container<int> a = *reinterpret_cast<Container<int>*>(_collection.pop());
Run Code Online (Sandbox Code Playgroud)
我的问题是,这是存储一组不相关类型的最佳方式吗?这也是存储和检索向量指针(重新解释转换)的首选方法吗?我环顾四周,看到提升有一个更好的解决方法,Boost :: Any,但由于这是一个学习项目,我想自己做(我也很好奇找到一个很好的理由正确使用reinterpret_cast).
考虑boost::any或者boost::variant是否要存储异构类型的对象.
在决定使用哪一个之前,先看看比较:
希望它能帮助您做出正确的决定.选择一个,以及从任何标准库容器的存储对象,std::stack<boost::any>, std::stack<boost::variant>,或任何其他.不要写自己的容器.
我再说一遍,不要写自己的容器.使用标准库中的容器.他们经过了充分的考验.