cereal icon indicating copy to clipboard operation
cereal copied to clipboard

Is there a way to register polymorphic types during program execution?

Open miki151 opened this issue 1 year ago • 3 comments

I have a large codebase with a certain class hierarchy where a header contains the base class, and the source file contains a number of subclasses inside a namespace {} block.

I do CEREAL_REGISTER_TYPE for all these subclasses in the source file, because they aren't visible outside of it. For some reason, when compiling my application with mingw, but only on some of my computers, it throws the unregistered polymorphic type exception when serializing.

As far as I can tell, I do everything correctly according to the docs, so I suspect this may be a compiler bug. I tried writing a minimal program that crashes to isolate the bug without success. I could try to work around it by declaring all the subclasses in the header, but it would be cumbersome.

I'm wondering if it's possible to register my subclasses inside a function in the source file, for example:

void registerTypes() {
  registerType<Subclass1, BinaryOutputArchive>();
  registerType<Subclass2, BinaryOutputArchive>();
// ...
}

And then call registerTypes() at the start of the program.

I'm pretty sure that boost serialization offered such an option. I've been digging through the cereal source code looking for code that I can call to register my types, but couldn't figure it out.

Is there anything else I could try to solve this issue?

miki151 avatar Mar 15 '24 20:03 miki151

Also want something like this

xiaodaxia-2008 avatar Mar 18 '24 02:03 xiaodaxia-2008

I have found that this works: cereal::detail::OutputBindingCreator<OutputArchiveType, SubclassType> tmp;

The constructor will expect cereal::detail::binding_name<SubclassType> to be specialized, you can do it by copying the first part of the CEREAL_REGISTER_TYPE macro or by modifying OutputBindingCreator to take the name in the constructor.

I think this would be a useful feature to add to cereal if any updates are considered.

miki151 avatar Apr 17 '24 09:04 miki151

您的邮件我已收到,谢谢合作!

redchairman avatar Apr 17 '24 09:04 redchairman