[英]generic shared_ptr as member of a class
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. 我希望将shared_ptr作为类的成员,但是shared_ptr管理的类型每次都不同,并且仅在运行时才知道。 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. 使用运行时多态性,这意味着定义一个通用基类,例如
Base
,并将通用接口声明为其中的虚函数,然后从中派生并在派生类中实现虚函数。 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. 或者,如果无法定义通用基类,则可以使用
boost::any
。 If you cannot use Boost, then you can define any
class yourself. 如果您不能使用Boost,那么您可以自己定义
any
类。 Search for Type Erasure on this site and in google. 在此网站和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): 以下是有关类型清除的两页文章,您可以在第二页上找到
boost::any
的实现(尽管不完整):
If the types are unrelated, you can use something like Boost.Any
for this. 如果类型不相关,则可以使用
Boost.Any
的方法。 Otherwise, do what @Nawaz says . 否则,请执行@Nawaz所说的 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.