Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can std::function be serialized?

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?

like image 978
danijar Avatar asked Aug 11 '13 15:08

danijar


2 Answers

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.

like image 54
Matthieu M. Avatar answered Oct 22 '22 20:10

Matthieu M.


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.

like image 5
Yakk - Adam Nevraumont Avatar answered Oct 22 '22 22:10

Yakk - Adam Nevraumont