Iterating over a struct in C++
Solution 1:
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 << "\n");
}
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
Solution 2:
You can't iterate over an object's data members. You can use std::ostream
's stream insertion operator to print individually however:
struct A
{
int a;
int b;
std::string c;
friend std::ostream& operator <<(std::ostream& os, A const& a)
{
return os << a.a << '\n'
<< a.b << '\n'
<< a.c << '\n';
}
};
And inside main:
int main()
{
A a = {5, 10, "apple sauce"};
std::cout << a;
}
Output:
5
10
apple sauce
Here is a demo.