Abh*_*bhi 6 c++ containers heterogeneous
我需要以(名称,值)的形式存储一系列数据点,其中值可以采用不同的类型.
我正在尝试为每个数据点使用类模板.然后对于我看到的每个数据点,我想创建一个新对象并将其推回到向量中.对于每种新类型,我需要先从模板创建一个新类.但是我不能存储在任何向量中创建的对象,因为向量对于所有条目都期望相同的类型.我需要存储的类型不能安装在继承层次结构中.他们是无关的.此外,将来可能会创建更多类型,我不想为每种新类型更改存储服务.有没有办法创建异构容器来存储这些条目?谢谢!
Mat*_* M. 10
boost::any
已被推荐,但它适用于任何事情,所以你不能期待它.
如果您提前知道各种类型,那么您最好使用boost::variant
.
typedef boost::variant<Foo, Bar, Joe> variant_type;
struct Print: boost::static_visitor<>
{
void operator()(Foo const& f) const { f.print(std::cout); }
template <class T>
void operator()(T const& t) const { std::cout << t << '\n'; }
};
void func(variant_type const& v) // not template
{
boost::apply_visitor(Print(), v); // compile-time checking
// that all types are handled
}
Run Code Online (Sandbox Code Playgroud)