问题描述
我正在使用 此处 提到的 STL 分配器.
我所做的唯一更改是我从一个名为 Object 的基类继承,并且我使用基类的 new 和 delete 函数进行分配.
I'm using the STL allocator mentioned here.
The only change I'm making is that I'm inheriting from a base class called Object, and I use base class' new and delete functions for allocation.
class MyAlloc :public Object{
......
}
我想使用基类的参数化构造函数,它基于发送到 STLAllocator 的参数,就像这样.
I want to use the parameterized constructor of the base class which will be based on parameter sent to the STLAllocator, which would be something like this.
MyAlloc(A *a) : Object(a) {
... }
然后像这样使用这个构造函数:
And then use this constructor like :
A *a = new A();
std::vector<int,MyAlloc<int> (a) > v;
我无法做到这一点.它导致编译错误:
'a'不能出现在常量表达式中
模板参数2无效
提前致谢..:)
I'm not able to achieve this. It is resulting in compilation error :
'a'cannot appear in a constant-expression
template argument 2 is invalid
Thanks in advance..:)
推荐答案
您将分配器的类型指定为模板参数,如果您不想要一个默认构造的,一个value 作为构造函数参数:
You specify the type of the allocator as a template argument and, if you don't want a default-constructed one, a value as a constructor argument:
std::vector<int,MyAlloc<int>> v((MyAlloc<int>(a)));
请注意,我添加了一对额外的括号以避免最烦人的解析".在这种情况下,我们无法避免使用大括号初始化,因为这将尝试使用初始化列表来填充向量.
Note that I added an extra pair of parentheses to avoid the "most vexing parse". In this case, we can't avoid that using brace-initialisation, since that will try to use the initialiser list to populate the vector.
这篇关于带有自定义构造函数的自定义 STL 分配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!