在助推聚变序列上使用的范围

Using range for on a boost FUSION sequence

本文关键字:范围      更新时间:2023-10-16

我正在尝试按如下方式打印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进行遍历,也可以使用hand-writen结构进行遍历。

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