gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:49:46 26 4
gpt4 key购买 nike

我有一个结构

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com