下面是地图的声明方式:std::map<const std::string,boost::any> data
我想创建一个将映射中的所有数据写入文件的函数,以及另一个读取数据并使用数据和相应的数据类型初始化映射的函数。
我读过大约10年前的一些老帖子,说这是不可能的,有什么改变了吗?
发布于 2018-04-28 01:00:54
如果您知道boost::any只引用了几个数据类型中的一个,那么您可以显式地检查它们,并显式地处理每种情况。例如,如果您使用Nlohmann Json库进行json序列化,则可以执行以下操作:
nlohmann::json json_rep;
for(auto const& kv: data)
{
auto const& key = kv.first;
auto const& value = kv.second;
auto const& type = value.type();
if(type == typeof(std::string))
json_rep[key] = boost::any_cast<std::string>(value);
else if(type == typeof(int))
json_rep[key] = boost::any_cast<int>(value);
else if(type == typeof(double))
json_rep[key] = boost::any_cast<double>(value);
else if(type == typeof(MyCustomType))
json_rep[key] = boost::any_cast<MyCustomType>(&value)->to_json();
// etc...
else
throw std::runtime_error("Invalid data type in data");
}不幸的是,如果any的数据类型没有界限,那么就没有通用的解决方案。
https://stackoverflow.com/questions/50065801
复制相似问题