C++ で std::vector<派生クラス> から std::vector<基底クラス> に変換する
さて、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));
こういう利用方法は覚えておくとよさそうですね。