Serialization and deserialization of `std::any` in C++ can be achieved by utilizing a combination of type information and stream manipulation. The `std::any` type allows you to store values of any type and can be serialized and deserialized by extracting the contained value and converting it to a format suitable for storage, such as JSON or binary.
Below is an example of how to serialize and deserialize `std::any` using JSON as the intermediary format. For this example, we'll use the `nlohmann/json` library for ease of JSON manipulation.
#include
#include
#include
// Using nlohmann::json for serialization and deserialization
using json = nlohmann::json;
// Function to serialize std::any
json serialize(const std::any& data) {
if (data.type() == typeid(int)) {
return json{ {"type", "int"}, {"value", std::any_cast(data)} };
} else if (data.type() == typeid(double)) {
return json{ {"type", "double"}, {"value", std::any_cast(data)} };
} else if (data.type() == typeid(std::string)) {
return json{ {"type", "string"}, {"value", std::any_cast<:string>(data)} };
}
throw std::runtime_error("Unsupported type");
}
// Function to deserialize std::any from json
std::any deserialize(const json& j) {
std::string type = j.at("type");
if (type == "int") {
return j.at("value").get();
} else if (type == "double") {
return j.at("value").get();
} else if (type == "string") {
return j.at("value").get<:string>();
}
throw std::runtime_error("Unsupported type");
}
int main() {
std::any myData = 42; // Can be int, double or std::string
// Serialization
json serializedData = serialize(myData);
std::cout << "Serialized: " << serializedData.dump() << std::endl;
// Deserialization
std::any deserializedData = deserialize(serializedData);
std::cout << "Deserialized Value: " << std::any_cast(deserializedData) << std::endl;
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?