Hard
Hand-rolled type erasure and small-buffer optimization
This is a minimal hand-rolled std::function-like type-erasure wrapper with a 16-byte inline buffer for small-buffer optimization (SBO). BigCallable has a std::array<int, 8> capture (32 bytes), far exceeding the 16-byte inline buffer. What happens when it's stored in AnyCallable?
main.cpp
class AnyCallable {
public:
template <typename F>
AnyCallable(F f) {
if constexpr (sizeof(F) <= sizeof(buffer_) && alignof(F) <= alignof(std::max_align_t)) {
new (&buffer_) F(std::move(f));
invoke_ = [](void* storage) { return (*reinterpret_cast<F*>(storage))(); };
heap_ = false;
} else {
ptr_ = new F(std::move(f));
invoke_ = [](void* storage) { return (*reinterpret_cast<F*>(storage))(); };
heap_ = true;
}
}
int operator()() { return invoke_(heap_ ? ptr_ : static_cast<void*>(&buffer_)); }
private:
alignas(std::max_align_t) unsigned char buffer_[16];
void* ptr_ = nullptr;
int (*invoke_)(void*) = nullptr;
bool heap_ = false;
};
struct BigCallable {
std::array<int, 8> data{1,2,3,4,5,6,7,8};
int operator()() const { return data[0]; }
};
int main() {
AnyCallable c(BigCallable{});
std::cout << c() << "\n";
}10 of 44 in Design Patterns