0

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
}
marital_weeping
  • 618
  • 5
  • 18
  • 2
    You seem to expect that the type, which needs to be known at compile time, would somehow magically be derived from the contents of the file that are only available at run time. C++ doesn't work this way. – Igor Tandetnik Nov 04 '22 at 04:01

0 Answers0