我正在尝试使用 boost::fast_pool_allocator
作为 std::list
的分配器, 但找不到 overload对于 construct()
使用可变参数模板。
#include <list>
#include <utility>
#include <boost/pool/pool_alloc.hpp>
int main()
{
typedef std::pair<int, int> Pair;
std::list<Pair, boost::fast_pool_allocator<Pair>> list;
list.emplace(list.begin(), 1, 2);
}
编译失败并出现以下错误(缩写):
stl_list.h:514:8: error: no matching function for call to ‘boost::fast_pool_allocator<blah>::construct(std::list<bleh>::_Node*&, int, int)'
查看 header file ,似乎boost::fast_pool_allocator
只有 construct()
的预 C++11 版本(一个指针和一个 const_reference)。
请注意,将列表定义为 std::list<Pair>
(即使用默认分配器)工作正常。
有解决办法吗?任何适配器或某种定义分配器特征的方法?我是分配器的新手,所以这对我来说有点黑暗。
我可以让它工作
list.emplace(list.begin(), Pair(1, 2));
但 1st) 我在生产中使用的实际类比 Pair
复杂得多我用这个例子,性能是最重要的(所以我真的可以使用就地构造),第二)理想情况下,我想直接替换 std::allocator
,因此我可以通过一行更改来衡量性能差异。
我在 Cygwin 中使用 g++ 4.9.2 和 boost 1.58.0 进行编译,我在使用 g++ 4.8.3 和 boost 1.55.0 的 linux 环境 (RHEL5.5) 中遇到了同样的问题。
最佳答案
template <typename T,
typename UserAllocator,
typename Mutex,
unsigned NextSize,
unsigned MaxSize >
struct my_pool_allocator:
boost::pool_allocator<T,UserAllocator,Mutex,NextSize,MaxSize>
{
using base=boost::pool_allocator<T,UserAllocator,Mutex,NextSize,MaxSize>;
using base::base;
template <typename U>
struct rebind
{
using other=my_pool_allocator<U, UserAllocator, Mutex, NextSize, MaxSize>;
};
using base::construct;
template<class...Args>
void construct(const typename base::pointer ptr, Args&&...args)
{ new (ptr) T(std::forward<Args>(args)...); }
};
或类似的东西。继承自fast_pool_allocator
,继承其构造函数,编写自定义rebind
,继承construct
,再添加一个construct
重载处理可变参数。
我怀疑应该能够编写一个“现代化分配器”模板来为您完成大部分工作。
template <class OldAllocator>
struct modernize_allocator:
OldAllocator
{
using base=OldAllocator;
using T=typename base::value_type;
using base::base;
template <typename U>
struct rebind
{
using other=modernize_allocator<typename base::rebind<U>::other>;
};
using base::construct;
template<class...Args>
void construct(const typename base::pointer ptr, Args&&...args)
{ new (ptr) T(std::forward<Args>(args)...); }
};
上面可能有拼写错误/错误:它只是一个解决方案的草图。
关于c++ - 使 boost::fast_pool_allocator 与可变参数模板一起工作 (emplace),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30036904/