在编译时捕获std :: function分配

Dav*_*Woo 6 c++ dynamic-memory-allocation c++11 std-function

我想只允许在我的代码库中使用std :: function,如果它不进行任何分配.

为此我可以编写类似下面的函数的东西,只用它来创建我的函数实例:

template< typename Functor>
std::function<Functor> makeFunction( Functor f)
{
    return std::function<Functor>(std::allocator_arg, DummyAllocator(), f);
}
Run Code Online (Sandbox Code Playgroud)

如果DummyAllocator在运行时被使用,它将断言或抛出.

理想情况下,我想在编译时捕获分配用例.

template< typename Functor>
std::function<Functor> makeFunction( Functor f)
{
   static_assert( size needed for function to wrap f < space available in function, 
   "error - function will need to allocate memory");

   return std::function<Functor>(f);
 }
Run Code Online (Sandbox Code Playgroud)

这样的事情可能吗?

Nia*_*all 2

您拥有的工厂方法可能是您最好的选择。

如果不合适,您可以选择实现一个适配器function;使用 作为成员变量实现接口std::function,以便适配器强制执行您的约束。

template <typename S>
class my_function {
  std::function<S> func_;
public:
  template <typename F>
  my_function(F&& f) :
  func_(std::allocator_arg, DummyAllocator(), std::forward<F>(f))
  {}
  // remaining functions required include operator()(...)
};
Run Code Online (Sandbox Code Playgroud)