简单的方法来实现小缓冲区优化任意类型擦除(像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
但它有一个小的缓冲区优化,因此如果 Concrete< Adaptee>
小于smth并且没有移动操作,它将被存储在其中。有没有一些通用库解决方案做到相当容易?为了强制在编译时只存储小的缓冲区?也许有人提出了标准化的建议?
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?
另一方面,您可以从头开始制作自己的解决方案,基于标准库例如 std :: aligned_storage
)。
On the other hand, you can just make your own solution from scratch, based on the standard library (e.g. std::aligned_storage
). This may still verbose from the view of users, but not too hard.
实际上,我实现了(不是建议) 任何
使用此类优化和一些相关的实用程序几年前。最近,libstdc ++的 std :: experimental :: any
的实现几乎完全使用了这个方法(但是, __
Actually I implemented (not proposed then) any
with such optimization and some related utilities several years ago. Lately, libstdc++'s implementation of std::experimental::any
used the technique almost exactly as this (however, __
prefixed internal names are certainly not good for ordinary library users).
我的实现现在使用一些常用助手来处理存储。这些助手轻松实现类型擦除存储策略(至少适合类似任何
的东西)。但我仍然对更一般的高级解决方案感兴趣,以简化接口重定向。
My implementation now uses some common helpers to deal with the storage. These helpers do ease to implement the type erasure storage strategy (at least fit for something similar to any
enough). But I am still interested in more general high-level solution to simplify the interface redirecting.