c++ - 派生类型的大括号初始化

标签 c++ c++14 list-initialization

我想要一个类型,它只是一个对象列表,可以派生自某个基类。也就是说,调用者得到一个 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)越好。

理论是会有一种方法可以引用 AllStuffAllMoreStuff作为参数,并能够使用 s1s2从中。其他方法只需要 AllMoreStuff并能够使用s3 (通过适当使用 dynamic_cast<MoreStuff*>(...) )。

但是,理论和现实还没有完全一致,如果您能帮助确定如何支撑初始化派生对象列表,我们将不胜感激。

最佳答案

您不能将 std::initializer_liststd::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/

相关文章:

c++ - 如何将 map 中的 copy_if 复制到 vector ?

c++ - 按键排序 std::unordered_map

c++ - 将字符串集中的元素添加到字符串集的 vector 中

C++ 正确使用来自另一个类的枚举

c++ - 为什么不对 initializer_list 中的值进行类型检查?

c++ - 如何在 C++ 中处理大小为 1,000,000,000 的数组?

c++ - 是否可以避免将参数复制到 lambda 函数?

c++ - 有效地从 unordered_set 中删除 unique_ptr

c++ - 列表初始化结合构造函数

c++ - c++ 11中结构数组的大括号初始化