我有一个结构
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/