& Quot; зерновые :: Исключение & Quot; при десериализации полиморфных типов с именованными парами значений (nvp)

я получаю «cereal :: Exception» с сообщением: «Сбой анализа JSON — при условии, что NVP не найден» при попытке десериализации полиморфного класса, сериализовавшего именованные пары значений.
Я делаю что-то неправильно?

вот заголовок:

#ifndef SERIALIZATION_H
#define SERIALIZATION_H

struct ComflabulationBase {
ComflabulationBase(float thingy = 0.0f, int dingy = 0.0f, bool mingy = false, const std::string& stringy = "") : thingy(thingy), dingy(dingy), mingy(mingy), stringy(stringy) {}
float thingy;
int dingy;
bool mingy;
std::string stringy;

template <class Archive>
void serialize(Archive & ar)
{
ar(
CEREAL_NVP(thingy),
CEREAL_NVP(dingy),
CEREAL_NVP(mingy),
CEREAL_NVP(stringy)
);
}
virtual ~ComflabulationBase() {}
virtual void sayType() { std::cout << "Base" << std::endl; }
};

struct Vector3
{
float x{0};
float y{0};
float z{0};

template <class Archive>
void serialize(Archive & ar)
{
ar(
CEREAL_NVP(x),
CEREAL_NVP(y),
CEREAL_NVP(z)
);
}
};

struct Comflabulation : public ComflabulationBase
{
Comflabulation(float bazingy = 1.5f, Vector3 vingy = Vector3()) : bazingy(bazingy), vingy(vingy) {}
~Comflabulation() {}
float bazingy;
Vector3 vingy;

template <class Archive>
void serialize(Archive & ar)
{
ar( cereal::base_class<ComflabulationBase>( this ),
CEREAL_NVP(bazingy),
CEREAL_NVP(vingy)
);
}

void sayType() {std::cout << "Derived" << std::endl; }

};
CEREAL_REGISTER_TYPE(Comflabulation)

#endif // SERIALIZATION_H

и мой файл cpp:

#include "cereal/cereal.hpp"#include "cereal/archives/binary.hpp"#include "cereal/archives/json.hpp"#include "cereal/types/polymorphic.hpp"#include <sstream>

#include "serialization.h"

template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}

int main (void)
{
std::stringstream ss;

{
std::unique_ptr<Comflabulation> one = make_unique<Comflabulation>();
std::unique_ptr<Comflabulation> two = make_unique<Comflabulation>(3.0f);
std::unique_ptr<Comflabulation> three = make_unique<Comflabulation>();
cereal::JSONOutputArchive oarchive(ss);
oarchive(one, two, three);
}

std::cout << ss.str() << std::endl;

{
std::unique_ptr<ComflabulationBase> one, two, three;
cereal::JSONInputArchive iarchive(ss);
iarchive(two, one, three);
two->sayType();
}std::cout << ss.str() << std::endl;

return 0;
}

0

Решение

Кажется, вам нужно сериализовать умный указатель на полиморфный базовый класс (см. http://uscilab.github.io/cereal/polymorphism.html):

std::unique_ptr<ComflabulationBase> one = make_unique<Comflabulation>();
std::unique_ptr<ComflabulationBase> two = make_unique<Comflabulation>(3.0f);
std::unique_ptr<ComflabulationBase> three = make_unique<Comflabulation>();

Спасибо Мануэлю Шиллеру за указание на это.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector