Search code examples
c++c++11

Easy way to implement small buffer optimization for arbitrary type erasure (like in std::function.)


I tend to use type erasure technique quite a bit. It typically looks like this:

class YetAnotherTypeErasure
{
public:
   // interface redirected to pImpl
private:
   // Adapting function
   template ...
   friend YetAnotherTypeErasure make_YetAnotherTypeErasure (...);

   class Interface {...};

   template <typename Adaptee>
   class Concrete final : public Interface { 
     // redirecting Interface to Adaptee
   };

   std::unique_ptr<Interface> pImpl_; // always on the heap
};

std::function does something similar, but it has a small buffer optimization, so if Concrete<Adaptee> is smaller than smth and has nothrow move operations, it will be stored in it. Is there some generic library solution to do it fairly easy? For enforcing small buffer only storing at compile time? Maybe something has been proposed for standardisation?


Solution

  • I found a reasonably nice solution for everyday code - use std::function

    With tiny library support to help with const correctness, the code get's down to 20 lines: https://gcc.godbolt.org/z/GtewFI