LoginSignup
12
6

More than 5 years have passed since last update.

C++ で std::vector<派生クラス> から std::vector<基底クラス> に変換する

Posted at

さて、C++ では次のような std::vector<派生クラス> から std::vector<基底クラス> への
暗黙的な変換はできません。

struct base{

};

struct derived : base{

};

std::vector<derived*> ary;

// base は derived の基底クラスなので変換を期待するが、こういう変換は無理
std::vector<base*> bases = ary;

ポインタ型からポインタ型へ変換する場合

両方共ポインタ型であればコンストラクタに iterator を渡すことで解決します。

std::vector<derived*> ary;

// コンストラクタに begin と end の iterator を渡せばコピーされる
std::vector<base*> bases(std::begin(ary), std::end(ary));

派生クラスを参照で受け取る

std::vector<T&> も同様に iterator でコピーすることができるんですが、std::vector で生の参照は保持できないので std::reference_wrapper を利用します。

std::vector<derived> ary;
std::vector<std::reference_wrapper<base>> bases(std::begin(ary), std::end(ary));

こういう利用方法は覚えておくとよさそうですね。

12
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
6