C++初始化std :: vector< std :: simolor_ptr< base>>在派生的类中
我有一个存储std :: vector< std :: simel_ptr< base>>
的多态基类。我想在派生的类中初始化此向量。这些向量的尺寸在编译时已知,并且在施工后不会改变。在我当前的解决方案中,我有一个纯虚拟函数initialize()
,它在每个派生中都被覆盖:
class Base {
public:
virtual void Initialize() = 0;
virtual ~Base() = default;
protected:
Base(std::size_t count) : m_data(count) {}
std::vector<std::unique_ptr<Base>> m_data;
};
class Derived1 : public Base {
public:
Derived1() : Base{ 8 } {}
void initialize() override {
m_data[0] = std::make_unique<Derived1>();
// ...
m_data[7] = std::make_unique<Derived1>();
};
};
class Derived2 : public Base {
public:
Derived2() : Base{ 24 } {}
void initialize() override {
m_data[0] = std::make_unique<Derived2>();
// ...
m_data[23] = std::make_unique<Derived2>();
};
};
但是,我对此解决方案不满意;部分是因为使用虚拟功能和
的冗余 m_data [0] = ...; ... m_data [n-1] = ...
。
我想分配m_data
这样:
m_data = {
std::make_unique<Derived1>(),
// ...
std::make_unique<Derived1>()
}
由于std :: simelod_ptr
s删除copy copy ctor而无法工作。
这是
” ?我正在使用C ++ 17。
I have a polymorphic base class storing a std::vector<std::unique_ptr<Base>>
. I would like to initialize this vector in the derived classes. The sizes of these vectors are known at compile time and do not change after construction. In my current solution I have a pure virtual function initialize()
which is overriden in each Derived:
class Base {
public:
virtual void Initialize() = 0;
virtual ~Base() = default;
protected:
Base(std::size_t count) : m_data(count) {}
std::vector<std::unique_ptr<Base>> m_data;
};
class Derived1 : public Base {
public:
Derived1() : Base{ 8 } {}
void initialize() override {
m_data[0] = std::make_unique<Derived1>();
// ...
m_data[7] = std::make_unique<Derived1>();
};
};
class Derived2 : public Base {
public:
Derived2() : Base{ 24 } {}
void initialize() override {
m_data[0] = std::make_unique<Derived2>();
// ...
m_data[23] = std::make_unique<Derived2>();
};
};
However, I am not pleased with this solution; Partly because of the use of a virtual function and the redundancy ofm_data[0] = ...; ... m_data[N-1] = ...
.
I would like to assign m_data
like this:
m_data = {
std::make_unique<Derived1>(),
// ...
std::make_unique<Derived1>()
}
which does not work because of std::unique_ptr
s deleted copy ctor.
Here is a more realistic sample of my code
What is the best way to initialize the vector in the derived classes? I am using C++17.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果虚拟函数是问题,则将其变成非虚拟函数。
而且,您可以简单地使用循环来摆脱重复的
:避免每种类型的代码相同的代码,在C ++,模板中有一个工具:
在这种情况下,模板参数是派生类型。这种习语有一个名称:奇怪的重复模板模式。
If the virtual function is a problem, then make it non-virtual.
You can simply use a loop to get rid of the repeated assignments:
To avoid redundancy from having identical code for each type, there is tool for that in C++, templates:
In this case, the template argument is the derived type. There is a name for such idiom: Curiously Recurring Template Pattern.