我想要一个类型,它只是一个对象列表,可以派生自某个基类。也就是说,调用者得到一个 Stuff
的列表。或 MoreStuff
(源自 Stuff
),并且至少可以对 Stuff 部分进行操作。
这听起来像 std::vector< std::unique_ptr< Stuff > >
大部头书。但是,我还想用大括号初始化程序对其进行初始化,这就是我要画空白的地方。
这或多或少是我正在尝试的:
#include <vector>
#include <memory>
#include <string>
struct Stuff {
std::string s1;
std::string s2;
};
using AllStuff = std::vector< std::unique_ptr< Stuff > >;
AllStuff const MyStuff = {
std::make_unique<Stuff>( Stuff{"1", "one"} )
};
struct MoreStuff : public Stuff {
std::string s3;
};
AllStuff const AllMoreStuff = {
std::make_unique<Stuff>( MoreStuff{"2", "two", "too"} )
};
或者,更确切地说,类似的东西。输入越少(用于向 vector 添加更多 Stuff
)越好。
理论是会有一种方法可以引用 AllStuff
或 AllMoreStuff
作为参数,并能够使用 s1
和 s2
从中。其他方法只需要 AllMoreStuff
并能够使用s3
(通过适当使用 dynamic_cast<MoreStuff*>(...)
)。
但是,理论和现实还没有完全一致,如果您能帮助确定如何支撑初始化派生对象列表,我们将不胜感激。
最佳答案
您不能将 std::initializer_list
与 std::unique_ptr
一起使用,因为 std::unique_ptr
是不可复制的,并且使用 进行初始化>std::initializer_list
表示复制。
您可能会切换到 std::shared_ptr
并将构造函数添加到您的结构中:
struct Stuff {
Stuff(const std::string& s1, const std::string& s2)
: s1(s1)
, s2(s2)
{}
std::string s1;
std::string s2;
};
using AllStuff = std::vector< std::shared_ptr< Stuff > >;
AllStuff const MyStuff = {
std::make_shared<Stuff>("1", "one")
};
struct MoreStuff : Stuff {
MoreStuff(const std::string& s1, const std::string& s2, const std::string& s3)
: Stuff(s1, s2)
, s3(s3)
{}
std::string s3;
};
AllStuff const AllMoreStuff = {
std::make_shared<MoreStuff>("2", "two", "too")
};
关于c++ - 派生类型的大括号初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47760556/