Search code examples
c++serializationtheorystd-function

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?


Solution

  • 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.