本文介绍了在 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
这篇关于在 C++ 中迭代结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!