C++ 使用RTTI克隆唯一指针的向量

C++ 使用RTTI克隆唯一指针的向量,c++,unique-ptr,C++,Unique Ptr,我想使用RTTI克隆唯一指针的向量 目前,有一个抽象基类,Node,还有派生类,Element和TextNode元素包含唯一的节点指针向量 我能够创建一个Element类型的对象,并将其移动到向量中。我希望能够克隆元素并将副本推送到向量中,但我正在与元素的副本构造函数进行斗争 这可能吗?如何使用RTTI克隆唯一指针?有没有更好的方法解决这个问题 #包括 #包括 #包括 #包括 结构节点{ virtual~Node()=默认值; 虚拟std::string toString()const=0; }

我想使用RTTI克隆唯一指针的向量

目前,有一个抽象基类,
Node
,还有派生类,
Element
TextNode
元素
包含唯一的
节点
指针向量

我能够创建一个
Element
类型的对象,并将其移动到向量中。我希望能够克隆
元素
并将副本推送到向量中,但我正在与
元素
的副本构造函数进行斗争

这可能吗?如何使用RTTI克隆唯一指针?有没有更好的方法解决这个问题

#包括
#包括
#包括
#包括
结构节点{
virtual~Node()=默认值;
虚拟std::string toString()const=0;
};
结构元素:节点{
元素()=默认值;
元素(常量元素和元素){
//克隆儿童
//对于(const auto&child:element.children)子级。向后推(std::make_unique(child));
}
元素(元素&&)=默认值;
std::string toString()常量重写{
std::string str=“”;
对于(const auto&child:children)str+=child->toString();
str+=”;
返回str;
}
性病媒儿童;
};
结构TextNode:节点{
std::string toString()const override{return“TextNode”;}
};
int main(){
元素根;
元素节点;
node.children.push_back(std::make_unique());
//这个副本不起作用,因为我不知道如何实现副本构造函数
root.children.push_back(std::make_unique(node));
root.children.push_back(std::make_unique(std::move(node));
root.children.push_back(std::make_unique());

std::cout您所要求的不能用RTTI直接完成,但可以通过手动检查类类型间接完成。因为您只有少量的类要检查,您可以这样做:

#包括
#包括
#包括
#包括
结构节点{
virtual~Node()=默认值;
虚拟std::string toString()const=0;
};
结构元素:节点{
元素()=默认值;
元素(常量元素和元素){
//克隆儿童
for(常量自动和子元素:element.children){
Node*n=child.get();
if(元素*e=动态(n)){
children.push_back(std::make_unique(*e));
}
else if(TextNode*t=dynamic_cast(n)){
children.push_back(std::make_unique(*t));
}
}
}
元素(元素&&)=默认值;
std::string toString()常量重写{
std::string str=“”;
用于(常量自动和子对象:子对象)
str+=child->toString();
str+=”;
返回str;
}
性病媒儿童;
};
结构TextNode:节点{
std::string toString()const override{return“TextNode”;}
};
int main(){
元素根;
元素节点;
node.children.push_back(std::make_unique());
root.children.push_back(std::make_unique(node));
root.children.push_back(std::make_unique(std::move(node));
root.children.push_back(std::make_unique());
std::cout clone());
}
元素(元素&&)=默认值;
std::string toString()常量重写{
std::string str=“”;
用于(常量自动和子对象:子对象)
str+=child->toString();
str+=”;
返回str;
}
std::unique_ptr clone()常量覆盖{
return std::make_unique(*this);
}
性病媒儿童;
};
结构TextNode:节点{
std::string toString()const override{return“TextNode”;}
std::unique_ptr clone()常量覆盖{
return std::make_unique(*this);
}
};
int main(){
元素根;
元素节点;
node.children.push_back(std::make_unique());
root.children.push_back(std::make_unique(node));
root.children.push_back(std::make_unique(std::move(node));
root.children.push_back(std::make_unique());
标准::cout