I can compile some code which fills a vector of raw pointers to a base class with pointers to a templated inherited class. But I've tried using the standard library and boost smart pointers instead of raw pointers, and the code doesn't compile. Can you explain why not?
This works:
vector<base*> vec
inherited<double>* elem = new inherited<double> >();
vec.push_back(elem);
This doesn't:
vector<auto_ptr<base> > vec
auto_ptr<inherited<double> >(new inherited<double> >());
vec.push_back(elem);
I don't really care whether or not what I'm trying to do is reasonable I'm just feeling out what's possible.
My full 60 LOC is here: https://gist.github.com/melvyniandrag/f432140c1aa216696bb6
Don't beat me up guys I've read a bit of C++ Templates: The Complete Guide (2002) and some posts here, but haven't been able to expediently connect the dots.
You can do this using std::shared_ptr
and std::static_pointer_cast
.
vector<shared_ptr<base> > vec;
shared_ptr<inherited<double> > elem(new inherited<double> >());
vec.push_back(static_pointer_cast<inherited<double>,base>(elem));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.