c++ - 迭代 C++ 中的结构

标签 c++ struct

我有一个结构

typedef struct A
{
    int a;
    int b;
    char * c;
}aA;

我想遍历结构的每个成员并打印其值。比如:

void print_struct_value(struct *A)
{
    for each member of struct A
    cout << "struct name . member name" << "value";
}

如何在 C++ 中做到这一点??

最佳答案

也许您可以使用 Boost Fusion/Phoenix 将一些东西串起来:

Coliru 上观看直播!

#include <boost/fusion/adapted/struct.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/phoenix/phoenix.hpp>
using boost::phoenix::arg_names::arg1;

#include <string>
#include <iostream>

struct A
{
    int a;
    int b;
    std::string c;
};

BOOST_FUSION_ADAPT_STRUCT(A, (int,a)(int,b)(std::string,c));

int main()
{
    const A obj = { 1, 42, "The Answer To LtUaE" };

    boost::fusion::for_each(obj, std::cout << arg1 << "\n");
}

Update: Recent versions of boost can use C++11 type deduction:

BOOST_FUSION_ADAPT_STRUCT(A,a,b,c);

输出:

1
42
The Answer To LtUaE

关于c++ - 迭代 C++ 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17660095/

相关文章:

c++ - 返回堆栈变量?

arrays - 如何在 Swift 4.0 中使用 WritableKeyPath 更新数组

struct - 戈朗 http.NewRequest : Invalid content-type

c - 我如何定义两个结构,每个都在第二个结构中使用? C语言

c++ - x = x+++++x; 的评估顺序是什么?是?

c++ - 具有枚举返回类型的函数无法在 C++ 类中解析

c++ - 尝试在 Qt 中连接隐藏信号的两种方式之间做出决定

c++ - 错误 : invalid declarator before with typedef

c++ - 指向函数中结构元素字段数组的指针

c - 程序读取文件但不应该跳过 "skips"行