gpt4 book ai didi

c++ - 如何新建一个 value_type 指针?

转载 作者:行者123 更新时间:2023-11-28 07:51:30 28 4
gpt4 key购买 nike

我正在写一个序列化和反序列化方法,我在反序列化的实现中遇到了一个问题:我不能new一个value_type,这实际上是一个Skill*

template <class T >
static istream &DeSerializePVector(istream& istream_, T& container)
{
typedef typename T::value_type ElementType;
size_t size;
istream_ >> size;
container.reserve(size);
container.resize(size);

for(typename T::iterator ite = container.begin(); ite != container.end(); ite++)
{
*ite = new *ElementType; //how can I initialize this type?
(*ite)->DeSerialize(istream_);
}

return istream_;
}

int main()
{
Skill* disease = Factory::CreateSkill ( SKILLTYPE_DISEASE );
Skill* purify = Factory::CreateSkill ( SKILLTYPE_PURIFY );
Skill* skills[2] = {disease, purify};
vector<Skill*> int_vector = Tools::MakeVector ( skills );
ofstream fileOut;
fileOut.open ( "data.txt", std::ofstream::binary );

ISerializable::SerializePVector( fileOut, int_vector );
fileOut.flush();
fileOut.close();

ifstream fileIn;
vector<Skill*> int_vector2;
fileIn.open ( "data.txt", std::ofstream::binary );
ISerializable::DeSerializePVector( fileIn, int_vector2 );
}

我应该如何完成这项工作?

最佳答案

假设 ElementType 有一个默认的构造函数,那么

*ite = new ElementType;

ElementType 已经是一个指针类型,那么你可能需要这个(C++11):

#include <type_traits>

*ite = new typename std::remove_pointer<ElementType>::type;

如果您不支持 C++11,则可以使用等效的 boost

关于c++ - 如何新建一个 value_type 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13678317/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com