Use C preprocessor to iterate over structure fields

I have several different C ++ structures and classes with fields with the same name that I have to copy between often. I would like to do something like: (in bashy pseudocode)

struct S{double a;
         double b;
         double c;};
class C{public: void set_a(double a);
                void set_b(double b);
                void set_c(double c); };
S s; C c;
#FOR F in FIELDSOF(S)
c.set_${F}(${F});
#ENDFOR

Is this a good idea, is there a way around either the C ++ preprocessor or the C ++ templates to achieve this? I am using g ++ and clang ++.

I already know the templates for engines like MAKO, and I also know that I can write a program to generate code. If you know, one of the things I would like to use to populate is to populate Google protobufs from C ++ structures.

+2
source share
2 answers

Boost, BOOST_FUSION_ADAPT_STRUCT Fusion . , .

- , .

: .

+3

. , , . , , :

struct S
{
    REFLECTABLE
    (
        (double) a,
        (double) b,
        (double) c
    )
};
class C
{
private:
    REFLECTABLE
    (
        (double) a,
        (double) b,
        (double) c
    )
public: 
    void set_a(double a);
    void set_b(double b);
    void set_c(double c); 
};

, , -:

struct assign_fields_visitor
{
    template<class FieldData1, class FieldData2>
    void operator()(FieldData1 fd1, FieldData2 fd2)
    {
        if (strcmp(fd1.name(), fd2.name()) == 0)
        {
            fd1.get() = fd2.get();
        }
    }
};

struct assign_fields
{
    template<class X, class FieldData>
    void operator()(X & x, FieldData f)
    {
        visit_each(x, boost::bind(assign_fields_visitor(), f, _1));
    }
};

template<class L, class R>
void assign(L & lhs, const R& rhs)
{
    visit_each(rhs, boost::bind(assign_fields(), boost::ref(lhs), _1));
}

, :

S s; C c;
assign(c, s);
+2

Source: https://habr.com/ru/post/1689254/


All Articles