I have the following macros that conditionally generate and initialize a member for classes:
#ifdef LIFETIME_TRACKING
#define DEFINE_TRACKER_MEMBER() mutable ::LifetimeTracker m_tracker
#define INITIALIZE_TRACKER_MEMBER(x) m_tracker(x)
#else
#define DEFINE_TRACKER_MEMBER() using dummy = void
#define INITIALIZE_TRACKER_MEMBER(x) /* ??? */
#endif
They are meant to be used as follows:
struct Example
{
int data;
Dependency dep;
DEFINE_TRACKER_MEMBER();
Example() : data(42), INITIALIZE_TRACKER_MEMBER(dep) { }
};
When LIFETIME_TRACKING is defined, everything is fine. When it is not defined, I could not figure out a way of making the constructor initializer list compile the , INITIALIZE_TRACKER_MEMBER(dep) syntax without either artificially increasing the class's size or making the syntax ugly and not friendly for clang-format (e.g. including the comma inside the macro, as INITIALIZE_TRACKER_MEMBER(, dep)).
The best I came up with is to have DEFINE_TRACKER_MEMBER create a dummy empty-struct member:
#define DEFINE_TRACKER_MEMBER() struct { } m_tracker
#define INITIALIZE_TRACKER_MEMBER m_tracker{}
However that increases the size of the parent class.
Is there any way I can keep the desired syntax and not incur a class size increase?
What about simply moving the comma into the macro itself?
#ifdef LIFETIME_TRACKING
#define DEFINE_TRACKER_MEMBER() mutable ::LifetimeTracker m_tracker;
#define INITIALIZE_TRACKER_MEMBER(x) ,m_tracker(x)
#else
#define DEFINE_TRACKER_MEMBER()
#define INITIALIZE_TRACKER_MEMBER(x)
#endif
struct Example
{
int data;
Dependency dep;
DEFINE_TRACKER_MEMBER()
Example() : data(42) INITIALIZE_TRACKER_MEMBER(dep) { }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With