プログラムで Config 構造を JSON ファイルに保存して読み取るようにしたいと考えています。
ただし、正しい JSON ファイルの生成に問題があります。おそらく問題は継承です。
JSON 出力 (正しくない):
{
"config": {
"confVector": [
{
"common": "a"
},
{
"common": "b"
}
]
}
}
予想される (正しい) JSON:
{
"config": {
"confVector": [
{
"common": "a",
"a" : 1
},
{
"common": "b",
"b" : "b"
}
]
}
}
コード :
共通要素を持つ基本構造体
struct Base
{
std::string common;
template <class Archive>
void serialize(Archive &ar)
{
ar(CEREAL_NVP(common));
}
};
2つの特定の構造
struct A : public Base
{
int a;
template <class Archive>
void serialize(Archive &ar)
{
ar(cereal::make_nvp("Base", cereal::base_class<Base>(this)));
ar(cereal::make_nvp("a", a));
}
};
struct B : public Base
{
std::string b;
template <class Archive>
void serialize(Archive &ar)
{
ar(cereal::make_nvp("Base", cereal::base_class<Base>(this)));
ar(cereal::make_nvp("b", b));
}
};
struct Config
{
std::vector<Base> confVector;
template <class Archive>
void serialize(Archive &ar)
{
ar(CEREAL_NVP(confVector));
}
};
CEREAL_REGISTER_POLYMORPHIC_RELATION(Base, A)
CEREAL_REGISTER_POLYMORPHIC_RELATION(Base, B)
メイン:jsonファイルへのテスト保存
int main()
{
std::string workPath = MAKE_STR(PLC_PROGRAM);
Config config;
A a;
a.a = 1;
a.common = "a";
B b;
b.b = "b";
b.common = "b";
config.confVector.push_back(a);
config.confVector.push_back(b);
std::ofstream outstream;
outstream.open(workPath + "/test.json");
{
cereal::JSONOutputArchive ar(outstream);
ar(cereal::make_nvp("config", config));
}
outstream.close();
}