2017-12-11 2 views
1

基本クラスから派生したオブジェクトのリストだけの型がありたいと思います。つまり、発信者はStuffまたはMoreStuffStuffから派生したもの)のリストを取得し、少なくともスタッフのパートで動作することができます。派生型のブレースの初期化

これは私に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"}) 
}; 

か、というと、そのようなことを。 (ベクトルにさらにStuffを追加するための)タイピングが少ないほど良いでしょう。

理論は、パラメータとしてAllStuff又はAllMoreStuffのいずれかへの参照を取り、そこからs1s2を使用することができるであろう方法があるであろうことであろう。他の方法は、AllMoreStuffしか使用せず、dynamic_cast<MoreStuff*>(...)の適切な使用によってs3を使用することができる。

しかし、理論と現実はまだあまり整理されておらず、派生したオブジェクトのリストをどのようにブレース初期化するかを決定する際の助けになります。

答えて

1

あなたはコピー不可で、std::initializer_listと初期化はコピーを意味std::unique_ptrstd::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") 
}; 
1

でC++ 17には、あなたが

MoreStuff{{"2", "two"}, "too"} 

を書くことができます集約のためのルールがベースを許可するように変更されているので、クラス(P0017参照)。

C++ 14以前では、MoreStuffは基本クラスが存在するため集計ではないため、集約初期化は適用されないため、必要な処理を行うコンストラクタを用意する必要があります。

ただし、C++ 17コンパイラを使用する場合でも、vectorを初期化する残りのコードは機能しません。含まれている型がコピー不可能な場合は、initializer_listコンストラクタを使用してvectorを初期化することはできません。詳細はthis questionを参照してください。

関連する問題