Home > Article > Backend Development > How to Iterate Over a Struct\'s Members in C Using Boost Fusion and Phoenix?
Iterating Over a Struct's Members in C
Given a struct definition:
<code class="c++">typedef struct A { int a; int b; char * c; } aA;</code>
we can iterate over its members and print their values using techniques like Boost Fusion/Phoenix.
Using Boost Fusion, we can adapt the struct for fusion:
<code class="c++">#include <boost/fusion/adapted/struct.hpp> BOOST_FUSION_ADAPT_STRUCT(A, (int, a)(int, b)(std::string, c));</code>
And then iterate over its members using Boost Phoenix:
<code class="c++">#include <boost/phoenix/phoenix.hpp> using boost::phoenix::arg_names::arg1; void print_struct_value(A const& obj) { boost::fusion::for_each(obj, std::cout << arg1 << "\n"); }</code>
An example usage:
<code class="c++">int main() { const A obj = { 1, 42, "The Answer To LtUaE" }; print_struct_value(obj); }</code>
This will output the member values:
1 42 The Answer To LtUaE
The above is the detailed content of How to Iterate Over a Struct\'s Members in C Using Boost Fusion and Phoenix?. For more information, please follow other related articles on the PHP Chinese website!