lundi 27 juillet 2020

Is there any way of creating a macro to define a constructor without needing to have the name of the containing class?

I have many classes which are like this:

struct A_Insert
{
    Data &d;
    A_Insert(d) : d(d){}

    // ...
}

struct A_Query
{
    Data &d;
    A_Query(d) : d(d){}

    // ...
}

struct B_Insert
{
    Data &d;
    B_Insert(d) : d(d){}

    // ...
}

struct B_Query
{
    Data &d;
    B_Query(d) : d(d){}

    // ...
}

The best thing I can think to do is define a macro like this:

#define Data_Query(name, body) struct name{Data &d; name(Data &d) : d(d) {} body}

but this leads to somewhat ugly code as I have to use parentheses to define my structs and my IDE doesn't handle it very well.

Data_Query(A_Insert, 
    int bind_params(stmt &stmt){}
    ...
)

I would like a macro which could allow me to get the name of the containing type for the constructor so I could write code like:

#define CONTAINING_TYPE
#define Data_Construct Data &d; CONTAINING_TYPE(Data &d) : d(d) {}

struct A_Insert { Data_Construct // ... }

and this way my IDE could treat it like a normal struct declaration. Any suggestions would be appreciated. A somewhat more readable alternative would be to do:

#define constructor CONTAINING_TYPE

and that way I could use it just like the JavaScript keyword while keeping it easier to copy and paste.

Aucun commentaire:

Enregistrer un commentaire