0

I am trying to print struct members as follows:

#include <iostream>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

struct Node {
    int a = 4;
    double b = 2.2;
};

BOOST_FUSION_ADAPT_STRUCT(Node, a, b)

int main() {
    Node n;
    for (auto el: n) { // What do I put instead of n here?
        std::cout << el << std::endl;
    }
    return 0;
}

This is wrong of course, since n is just a struct. How do I put for a sequence that the range for can work with instead of n?

AlwaysLearning
  • 7,257
  • 4
  • 33
  • 68

1 Answers1

2

You cannot use range-based for for this case. It's metaprogramming, each member iterator has its own type. You can traverse using fusion::for_each, or with hand-writen struct.

#include <iostream>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/for_each.hpp>

struct Node {
    int a = 4;
    int b = 2.2;
};

BOOST_FUSION_ADAPT_STRUCT(Node, a, b)

struct printer
{
   template<typename T>
   void operator () (const T& arg) const
   {
      std::cout << arg << std::endl;
   }
};

int main() {
    Node n;
    boost::fusion::for_each(n, printer());
    return 0;
}
ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • Nice! Is there a way to get to the field's name inside `printer::operator()`? – AlwaysLearning Dec 10 '15 at 09:34
  • @AlwaysLearning no. For this case you should write your own metastruct, that will do this traversing struct from `fusion::begin` to `fusion::end` and calling special metafunctions. – ForEveR Dec 10 '15 at 09:38