我倾向于使用类型擦除技术.它通常看起来像这样:
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
};
Run Code Online (Sandbox Code Playgroud)
std::function做类似的事情,但它有一个小的缓冲区优化,所以如果Concrete<Adaptee>小于smth并且没有进行移动操作,它将被存储在其中.是否有一些通用的库解决方案来做到这一点相当容易?为了强制只在编译时存储的小缓冲区?也许已经提出了标准化的建议?
我为日常代码找到了一个相当不错的解决方案 - 使用 std::function
借助小型库支持来帮助确保 const 正确性,代码可减少至 20 行: https: //gcc.godbolt.org/z/GtewFI