0

我在写一个序列化和反序列化的方法,在实现的时候遇到了一个问题deserialize:I can't newa 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 );
}

我应该如何得到这份工作?

4

1 回答 1

1

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

*ite = new ElementType;

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

#include <type_traits>

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

如果您没有 C++11 支持,则可以使用boost等价的。

于 2012-12-03T06:46:49.483 回答