I want to have a shared_ptr as a member of a class, but the type that the shared_ptr manages is different each time and is only known at run time. Is there any way to declare such a member and init it later?
Yes.
Use runtime polymorphism which means define a common base class, say Base
and declare the common interfaces as virtual functions in it, then derive from it and implement the virtual functions in the derived classes. If you do so, then you can use like this:
std::share_ptr<Base> ptr;
//now ptr can store an instance of any derived class from Base
Or you could use boost::any
if it is not possible to define a common base class. If you cannot use Boost, then you can define any
class yourself. Search for Type Erasure on this site and in google.
The following is a two-pages article on Type Erasure, and you can find an implementation of boost::any
on the second page (though not complete):
If the types are unrelated, you can use something like Boost.Any
for this. Otherwise, do what @Nawaz says .
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.