#include <iostream>
#include <queue>
#include <any>
// 自定义类型
struct CustomType1 {
int value;
};
struct CustomType2 {
double data;
};
class FactoryTestResult_t
{
public:
int32_t id;
int32_t count_number;
std::string data;
int8_t result;
};
int main()
{
// 定义队列
std::queue<std::any> q;
FactoryTestResult_t data;
data.id=1;
data.count_number=2;
data.data="11";
data.result = 1;
// 入队操作
q.push(data); // 存入 FactoryTestResult_t 类型数据
q.push(CustomType1{10}); // 存入 CustomType1 类型数据
q.push(CustomType2{3.14}); // 存入 CustomType2 类型数据
// 出队操作,并使用 any_cast 进行类型转换
while (!q.empty())
{
std::any item = q.front();
q.pop();
if (item.type() == typeid(CustomType1))
{
CustomType1 c1 = std::any_cast<CustomType1>(item);
std::cout << "CustomType1: " << c1.value << std::endl;
}
else if (item.type() == typeid(CustomType2))
{
CustomType2 c2 = std::any_cast<CustomType2>(item);
std::cout << "CustomType2: " << c2.data << std::endl;
}
else if (item.type() == typeid(FactoryTestResult_t))
{
FactoryTestResult_t c2 = std::any_cast<FactoryTestResult_t>(item);
std::cout << "FactoryTestResult: " << c2.id << std::endl;
}
}
return 0;
}
C++ 17 : 一个队列使用 std::any存储多种自定义类型的数据
于 2024-04-30 10:29:53 首次发布