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

时间:2015-08-27 16:04:25

标签: c++ c++11 dynamic-memory-allocation std-function

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

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

template< typename Functor>
std::function<Functor> makeFunction( Functor f)
{
    return std::function<Functor>(std::allocator_arg, DummyAllocator(), f);
}

如果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);
 }

这样的事情可能吗?

3 个答案:

答案 0 :(得分:2)

我写了一个没有分配的std::function替换,因为std::function确实需要分配内存,这里只有candidate

答案 1 :(得分: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()(...)
};

答案 2 :(得分:0)

在您的库中提供std::function分配器支持,只需为std::function提供一个不起作用的分配器。

template< typename t >
struct non_allocator : std::allocator< t > {
    t * allocate( std::size_t n ) { throw std::bad_alloc{}; }
    void deallocate( t * ) {}

    non_allocator() = default;
    template< typename u >
    non_allocator( non_allocator< u > const & ) {}

    template< typename u >
    struct rebind { typedef non_allocator< u > other; };
};

template< typename t, typename u >
bool operator == ( non_allocator< t > const &, non_allocator< t > const & )
    { return true; }

template< typename t, typename u >
bool operator != ( non_allocator< t > const &, non_allocator< t > const & )
    { return false; }

不幸的是,这在GCC中不起作用,因为它甚至没有为allocator_arg声明任何function构造函数。即使在Clang中,编译时错误也是不可能的,因为它不幸地在常量值上使用运行时if来决定是否使用分配器。

相关问题