在 C++ 中迭代结构

2021-12-23 00:00:00 struct c++

我有一个结构

typedef struct A{一个;国际b;字符 * c;}aA;

我想遍历结构的每个成员并打印其值.类似的东西:

void print_struct_value(struct *A){对于结构 A 的每个成员cout<<结构名称.成员名称"<<价值";}

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

解决方案

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

在 nooli> rel="rar>!

#include #include #include 使用 boost::phoenix::arg_names::arg1;#include <字符串>#include 结构A{一个;国际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 << "
");}

<块引用>

更新:boost 的最新版本可以使用 C++11 类型推导:

BOOST_FUSION_ADAPT_STRUCT(A,a,b,c);

输出:

142LtUaE 的答案

I have a structure

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

I want to iterate over each an every member of the structure and print its value. Something like:

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

How can this be done in C++ ??

解决方案

Perhaps you can string something together using Boost Fusion/Phoenix:

See it live on 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 << "
");
}

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

BOOST_FUSION_ADAPT_STRUCT(A,a,b,c);

Output:

1
42
The Answer To LtUaE

相关文章