This is a theoretical question. Say there are some objects which among others contain lists of callback functions subscribed to events of those objects. Now we want to store those objects on disk. Is a std::function
serializable?
No.
Whenever using type erasure (ie, hiding implementation details behind an interface), the only operations available without knowing the dynamic type of the object are those provided by the interface.
There is no serialization in the C++ Standard, and there is no easy way to serialize functions either (without reflection), thus the std::function
interface does not provide serialization.
On the other hand, nothing prevents you from using a Callback
base class that provides serialization support.
std::function
is a type erasure object that obeys value semantics. It exposes copy/move construction and assignment, and execution of a particular signature, and destruction.
None of these are serialization.
Internally, the typical implementation of std::function
is to create a implementation helper template
class on its constructed-from argument, which wraps the above operations on the argument, then the std::function
itself delegates its implementation of those operations to the helper object.
The layout of that helper object is going to be dependent on the layout of the argument constructed from (on top of its existence being optional, and its implementation being implementation dependent).
You could try to create a similar object that supports serialization, but a type erasure object relies on the fact that the type being erased already implements the operation in question. Which means you can only construct a type erased function-with-serialization from an object that supports function-with-serialization interface at least at the ducktype level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With