Lets suppose I have such classes hierarchy:
enum class Type { DUMMY };
struct Base {
int a;
explicit Base(int a) : a(a) {}
virtual ~Base() {}
virtual Type type() = 0;
};
struct Foo1 : public Base {
double b;
Foo1(int a, double b) : Base{a}, b(b) {}
Type type() override { return Type::DUMMY; }
};
all derived from Base
using single inheritance and not defined
any virtual
methods, except overriding type()
method.
And I want to have meta info for each derived from Base
to serialization and debug output. And as I see boost fusion is what I want:
#include <iostream>
#include <string>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/mpl.hpp>
#include <boost/fusion/include/zip.hpp>
#include <boost/mpl/range_c.hpp>
namespace fusion = boost::fusion;
namespace mpl = boost::mpl;
enum class Type { DUMMY };
struct Base {
int a;
explicit Base(int a) : a(a) {}
virtual ~Base() {}
virtual Type type() = 0;
};
struct Foo1 : public Base {
double b;
Foo1(int a, double b) : Base{a}, b(b) {}
Type type() override { return Type::DUMMY; }
};
BOOST_FUSION_ADAPT_STRUCT(Foo1, (double, b))
template <typename Sequence> struct XmlFieldNamePrinter {
XmlFieldNamePrinter(const Sequence &seq) : seq_(seq) {}
const Sequence &seq_;
template <typename Index> void operator()(Index idx) const {
std::string field_name =
fusion::extension::struct_member_name<Sequence, idx>::call();
std::cout << '<' << field_name << '>' << fusion::at<Index>(seq_) << "</"
<< field_name << ">\n";
;
}
};
template <typename Sequence> void printXml(Sequence const &v) {
typedef mpl::range_c<unsigned, 0, fusion::result_of::size<Sequence>::value>
Indices;
fusion::for_each(Indices(), XmlFieldNamePrinter<Sequence>(v));
}
int main() {
Foo1 saveMe = {3, 3.4};
printXml(saveMe);
}
But how handle Base
data memebers?
I do not want include their description into BOOST_FUSION_ADAPT_STRUCT(Foo1
,
like this:
BOOST_FUSION_ADAPT_STRUCT(Foo1,
(int, a)
(double, b))
because of I have to do it for every struct that inherit from Base
,
so I would prefer syntax similar to this(not compiled of course):
BOOST_FUSION_ADAPT_STRUCT(Base, (int, a))
BOOST_FUSION_ADAPT_STRUCT(Foo1,
(Base, __parent__)
(double, b))
How can I achieve similar syntax?