c++ - 将对象快照保存到文件的最佳方法

标签 c++ visual-studio-2005 file-io

将对象的公共(public)内容输出到人类可读文件的最佳方式是什么?我正在寻找一种不需要我知道类的所有成员的方法,而是使用编译器告诉我存在哪些成员以及他们的名字是什么。必须有宏或类似的东西,对吧?

人为的例子:

class Container
{
public:
    Container::Container() {/*initialize members*/};
    int stuff; 
    int otherStuff;
};
Container myCollection;

我希望能够按照“myCollection: stuff = value, otherStuff = value”的顺序查看输出。 但是如果另一个成员被添加到容器中,

class Container
{
public:
    Container::Container() {/*initialize members*/};
    int stuff;
    string evenMoreStuff;
    int otherStuff;
};
Container myCollection;

这一次,这个快照的输出将是“myCollection: stuff = value, evenMoreStuff=value, otherStuff = value”

是否有宏可以帮助我完成此操作?这可能吗? (另外,我无法修改 Container 类。) 另一个注意事项:我最感兴趣的是 VS 中的潜在宏,但也欢迎其他解决方案。

最佳答案

您正在寻找的是“[反射]( http://en.wikipedia.org/wiki/Reflection_(computer_science)#C.2B.2B) ”。

我通过 Google 搜索“C++ 反射”找到了两个有希望的链接:

http://www.garret.ru/cppreflection/docs/reflect.html

http://seal-reflex.web.cern.ch/seal-reflex/index.html

关于c++ - 将对象快照保存到文件的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/281787/

相关文章:

c++ - Memset 不填充整个指针数组 C++

c++ - c++ 中有没有一种方法可以确保类成员函数不会更改任何类数据成员?

c - C 中的临时文件

c++ - 试图找出为什么我的代码保持无限循环

java - 如何用Ant编译构建C++项目?

visual-studio - .vsprops 文件中的 'Delimiter' 和 'InheritsFromParent' 属性是什么意思?

windows - Visual Studio 2005 是否与 windows 8.1 64 位兼容?

c++ - 在 VS 2005 中仅转储部分内存

caching - WinXP 中文件的内存映射和系统缓存行为

java - 使用 IOUtils 和 ImageIO 写入图像文件有什么区别