如何创建一个带有自定义分配器的std ::函数? [英] How can I create a std::function with a custom allocator?
问题描述
保存一些代码让我说我有一个名为 MyAlloc
的自定义分配器,我已成功使用 std :: vector< int>
如下:
To save some code lets say I have a custom allocator named MyAlloc
which I have successfully used with a std::vector<int>
as follows:
std::vector<int,MyAlloc<int>> vec;
现在我想使用自定义分配器在std ::函数中保存一个lambda,是吗?
now I want to save a lambda in a std::function using the custom allocator, how do I do it?
我的失败尝试:
int i[100];
std::function<void(int)> f(MyAlloc<void/*what to put here?*/>{},[i](int in){
//...
});
推荐答案
根据标准, a href =http://en.cppreference.com/w/cpp/memory/allocator_arg =nofollow>标签类型作为第一个参数,表示您要使用自定义分配器: / p>
According to the standard, you need to give a tag type as the first argument to indicate that you want to use a custom allocator:
std::function<void(int)> f(std::allocator_arg, MyAlloc<char>{}, [i](int in){
//...
});
正如 @ Casey 和 @ Potatoswatter 在注释中,给分配器的模板参数类型无关紧要,因为它是一个对象类型。所以 char
在这里很好。
As pointed out by @Casey and @Potatoswatter in the comments, the template argument type given to the allocator does not matter, as long as it's an object type. So char
is fine here.
这篇关于如何创建一个带有自定义分配器的std ::函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!