使用 range for on a boost FUSION 序列

Using range for on a boost FUSION sequence

我正在尝试按如下方式打印 struct 成员:

#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;
}

这当然是错误的,因为 n 只是一个 struct。我如何输入 range for 可以代替 n 的序列?

您不能在这种情况下使用 range-based for。它是元编程,每个成员迭代器都有自己的类型。您可以使用 fusion::for_each 或手写结构进行遍历。

#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;
}