Last active
December 15, 2015 21:29
-
-
Save ncaq/5325867 to your computer and use it in GitHub Desktop.
vectorの中にあるshared_ptr全てをアップキャストする方法がググっても見つからないので自作してみました.
絶対なにかまともな方法が有るはず.誰か教えてください.
解決しました https://twitter.com/ncaq/status/320510856112771072
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <memory> | |
#include <type_traits> | |
using namespace std; | |
class Super | |
{ | |
public: | |
virtual ~Super(){}; | |
}; | |
class Sub:public Super | |
{ | |
}; | |
template <typename S,typename D> | |
vector<shared_ptr<S>> vectorUpCast(const vector<shared_ptr<D>>& d) | |
{ | |
static_assert(is_base_of<S,D>::value,"is not inheritance");//継承関係に有るかコンパイル時にチェック | |
vector<shared_ptr<S>> s; | |
for(auto i:d) | |
{ | |
s.push_back(i);//効率物凄く悪そう | |
} | |
return s; | |
} | |
int main() | |
{ | |
vector<shared_ptr<Sub>> sub; | |
//vector<shared_ptr<Super> super = de;//これは自動でアップキャストしてくれない… | |
//vector<shared_ptr<Super>> super = vectorUpCast<Super,Sub>(sub);//だから函数を使う,誰かこんな感じの標準的なライブラリ知りませんか | |
vector<shared_ptr<Super>> super(sub.begin(),sub.end());//解決 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment