c++ - 使用 range for on a boost FUSION 序列

标签 c++ c++11 boost-fusion

我正在尝试打印 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;
}

关于c++ - 使用 range for on a boost FUSION 序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34197759/

相关文章:

c++ - 允许人们在没有端口转发的情况下主持他们自己的多人游戏吗?

c++ - 64 位进程上的 ReadProcessMemory 总是返回错误 299

c++ - 在 C++ 中设置文件修改时间的可移植方法?

c++ - std::function 到对象的成员函数和对象的生命周期

c++ - Boost::fusion、Eigen 和 zip 变换

c++ - 在附加之前将 "number 0"转换为 char

c++ - Qt-Qml : Binding checkbox to QAbstractListModel

c++ - condition_variable::wait_for 总是在等待?

c++ - 如何遍历 boost::fusion 序列?

c++ - 如何将齐次 fusion::vector 转换为 (std/boost)::数组