[英]C++ container for heterogeneous POD types
Is there a form of heterogeneous container, that is able to to store for example different primitive types (such as int
, float
, double
)? 是否存在某种形式的异构容器,该容器能够存储例如不同的原始类型(例如
int
, float
, double
)?
Ultimately I'd like to be able to use the elements in calculations without referring to the type explicitly, for example auto res = a + b
, where the operands a
and b
are elements pulled out of the container and could be of same or different types. 最终,我希望能够在计算中使用元素而不显式引用类型,例如
auto res = a + b
,其中操作数a
和b
是从容器中拉出的元素,并且可以相同或不同类型。
With C++17 you can use std::any with any container. 在C ++ 17中,您可以将std :: any与任何容器一起使用。 With older C++ versions you can use boost::any .
对于较旧的C ++版本,您可以使用boost :: any 。
#include <iostream>
#include <vector>
#include <any>
struct A
{
int a;
explicit operator int() const { return a; }
};
struct B
{
double b;
explicit operator double() const { return b; }
};
int main()
{
A a{ 5 };
B b{ 6.};
std::vector<std::any> v;
v.push_back(3 );
v.push_back(4.);
v.push_back(a );
v.push_back(b );
for (auto const e : v)
{
if (e.type() == typeid(double))
std::cout << std::any_cast<double>(e) << std::endl;
if (e.type() == typeid(B))
std::cout << (double)std::any_cast<B>(e) << std::endl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.