写广义保存和读 [英] Writing generalized save and read

查看:202
本文介绍了写广义保存和读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个类来从/到文件读取和写入对象。我使用模板关键字来实现此目标。

I want to write a class for both reading and writing objects from/to file. I use the template keyword to achive this aim.

 template<class T>
 class A{
  private:
   std::string filePath;//This will use to indicate the path of proper file.
  public:
    void save(T a){
     //write the given object to the file. The path is fetched by filePath
    }
    std::list<T> read(){
    //read the file and put each line in the list. The path is fetched by filePath
    }
    A(std::string path):filePath(path){}
 };

如果我使用这个方法,一切都很好,当我使用它与原始类型,如int或浮动。但是当我想使用对象时,问题出现,例如,Circle,Rectacngle。
我应该如何解决问题

If I use this method, everything is fine when I used it with primitive types like, int, or float. But the problem arise when I want to work with object, e.g, Circle,Rectacngle. What should I do to solve the problem

推荐答案

您可能需要序列化(或者甚至持续性,例如应用程序检查点 ...)。

You probably want serialization (or perhaps even persistency, e.g. application checkpointing...). Sometimes it is called data pickling.

您可以使用

You could use the s11n library (giving templates for serializing C++ data).

您还可以定义运算符<< operator>> 在你自己的类上,所以用 Rectangle r; 将代码 std :: cout<< r; std :: cin> r;

You could also define your operator << and operator >> on your own classes, so with your Rectangle r; you would code std::cout << r; and std::cin >> r;

您可以考虑使用文本序列化格式,例如 JSON (或YAML或XML ...)eg使用 jsoncpp

You could consider textual serialization formats like JSON (or YAML or XML...) e.g. using jsoncpp

序列化任意图更困难序列化树状数据结构(因为循环引用和共享指针....)。

Serializing arbitrary graphs is much more difficult that serializing tree-like data structures (because of circular references and shared pointers....).

在C ++中没有简单的自动方式获取序列化设施,你可能不想要一个。想象一下,你代表了你的一些类中 Person -s之间的人类婚姻。出于效率原因,您可能希望有两个表( std :: map<(Person,Person> 丈夫和另一个映射丈夫到每个妻子(你想要两个表,因为你经常询问一些女人的丈夫,或一些人的妻子)。但你可能不想序列化这两个表(他们是不知何故冗余),只是一组丈夫+妻子对。这是为了说明序列化通常是特定于应用程序的。

There is no simple automatic way to get serialization facilities in C++, and you probably don't want one. Imagine that you are representing human marriages between Person-s in some of your class. For efficiency reasons you may want to have two tables (of type std::map<(Person,Person>), one mapping wife to every husband and another mapping husband to every wife (you want both tables because you often query the husband of some woman, or the wife of some man). But you probably don't want to serialize both of these tables (they are somehow "redundant"), just a set of husband+wife pairs. This is to illustrate that serialization is often application specific.

这篇关于写广义保存和读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆