I'd like to be able to recover objects of the templated class A<T>
using the deserialize_from_file
method below. However, I'd like to not refer to the type of T
explicitly as int
and double
while calling the deserialize_from_file
method and rather somehow the compiler deduce them via auto
. How do I accomplish this?
#include <iostream>
#include <fstream>
#include <cereal/archives/json.hpp>
template <typename T>
struct A {
T value{};
A() = default;
explicit A(T value) : value(value) {}
template <class Archive>
void serialize(Archive &archive) {
archive(value);
}
template<typename OutputArchiveType>
void serialize_to_file(const std::string &filename) const {
std::ofstream ofs(filename);
OutputArchiveType oa(ofs);
oa << *this;
}
};
template<typename InputArchiveType, typename T>
auto deserialize_from_file(const std::string& file_name) {
std::ifstream ifs(file_name);
InputArchiveType ia(ifs);
A<T> a;
ia >> a;
return a;
}
int main() {
A<int> a1(42);
A<double> a2(1.2);
a1.serialize_to_file<cereal::JSONOutputArchive>("a1.json");
a2.serialize_to_file<cereal::JSONOutputArchive>("a2.json");
auto a1_des = deserialize_from_file<cereal::JSONInputArchive, int>("a1.json"); // would like to avoid explicitly specifying the type int here
auto a2_des = deserialize_from_file<cereal::JSONInputArchive, double>("a2.json"); // would like to avoid explicitly specifying the type double here
}