C++ iterate into nested struct field with boost fusion adapt_struct(C++ 使用 boost fusion adapt_struct 迭代到嵌套结构域)
问题描述
两个stackoverflow 答案 建议使用 fusion adapt_struct 迭代结构字段的方法.这种方法看起来不错.但是,如何迭代到一个本身就是结构体的字段?
Two stackoverflow answers suggest the approach using fusion adapt_struct to iterate over struct fields. The approach looks nice. However, how do you iterate into a field which itself is a struct?
按照前面的答案,我想出了下面的代码.问题在于代码无法编译的#if 0"子句.作为替代解决方案,我创建了decode()"函数来获取指向目标参数的空指针.这有效,但在编译时丢失了类型信息.有更好的解决方案吗?
Following the previous answers, I come up with the code below. The problem is at the "#if 0" clause the code does not compile. As an alternative solution I created "decode()" function to take a void pointer to the target argument. That works, but loses the type information at compile time. Is there a better solution?
我在 wikipedia 上看到,而不是传递您可以使用的类型字符串intype"typeid 和 dynamic_cast.但这只会是一个很小的改进.我正在寻找一种对 C++ 或 boost 语言设计更内在的解决方案.
I have seen on wikipedia instead of passing a type string "intype" you can use typeid and dynamic_cast. But that will only be a minor improvement. I'm looking for a solution that is more intrinsic to C++ or boost language design.
推荐答案
我做了 您可以在我的博客网站上看到的您想要的示例.在这种情况下,它是一个使用嵌套结构的 JSON 序列化程序.自从我在 Boost.Serialization 库中看到它以来,它使用了更多 Boost"解决方案.(另见下文和在 Coliru 上直播.)
I made an example of what you want that you can see at my blog site. In this is case it's a JSON serializer that works with nested structs. It uses a 'more Boost' solution since I saw it in the Boost.Serialization library. (See also below and live on Coliru.)
该解决方案使用结构的 Fusion Sequence 适配和一个遍历对象成员(递归)的元函数 - 使用 Boost.TypeTraits 和特定类型的不同特征.
The solution uses Fusion Sequence adaptation of structs and a metafunction that walks object members (recursively) - using Boost.TypeTraits and different traits for specific types.
你可以看到一个更复杂的googlecode corbasim 项目网站上的相同解决方案示例,用于创建运行时自反 API.
You can see a more complex example of the same solution at the site for googlecode corbasim project for creating an run-time reflexive API.
看到它在 Coliru 上直播
See it Live on Coliru
这篇关于C++ 使用 boost fusion adapt_struct 迭代到嵌套结构域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!