简体   繁体   English

将类存储在boost :: property_tree中

[英]Storing classes in a boost::property_tree

I'm working on a program to record information about the variables within a program. 我正在研究一个程序,以记录有关程序中变量的信息。 I'd like to group this information by file -> function -> variable. 我想按文件->函数->变量对这些信息进行分组。

The boost::property_tree seemed like a good fit for this as I could store an Access object at a path in the tree ( file.function.variable ) and then easily convert the tree to XML, JSON, etc. boost :: property_tree似乎很适合此操作,因为我可以将Access对象存储在树中的路径( file.function.variable )中,然后轻松地将树转换为XML,JSON等。

Say I'm recording the number of uses of a variable. 假设我正在记录变量的使用次数。 I can have a class Access that keeps track of the number of writes and reads to a variable. 我可以拥有一个Access类,该类可以跟踪对变量的写入和读取次数。 I can then store this object at file.function.variable in the tree. 然后,我可以将该对象存储在树中的file.function.variable中。 Each time the variable is accessed I can find the variable in the tree and update information about it. 每次访问变量时,我都可以在树中找到该变量并更新有关它的信息。

However, I cannot figure out how to store a class in the tree. 但是,我无法弄清楚如何在树中存储类。 I assume there is something I need to implement or subclass, but the documentation doesn't address what I'm trying to do. 我认为我需要实现某些东西或将其子类化,但是文档并未解决我要尝试做的事情。

Is there a solution to my problem? 我的问题有解决方案吗? Is there a better alternative to boost::property_tree? 有没有更好的替代方法来增强boost :: property_tree?

Thank you. 谢谢。

boost::property_tree is designed to hold text data . boost::property_tree用于保存文本数据 That's what makes it suitable for exporting to XML, JSON, etc. 这就是使其适合导出到XML,JSON等的原因。

Modify your class Access so it includes methods for converting to/from text and store that text in the tree. 修改您的类Access以便它包括用于与文本转换的方法以及将该文本存储在树中的方法。

You could drop the idea of the tree and just stick with a flat map of key value pairs. 您可以放弃树的概念,而只坚持键值对的平面映射。

Example: 例:

std::map<std::string, Access> accesses;
// add one access
accesses["file.function.variable"] += 1;

You just need to write a routine that produces the JSON from its content, which should be straightforward. 您只需要编写一个从其内容生成JSON的例程,这应该很简单。 (Assuming the first part of the key is always the file, the second is always the function, the third is always the variable.) (假设键的第一部分始终是文件,第二部分始终是函数,第三部分始终是变量。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM