Is equivalence decltype (* this) from a static method?

I have some macros that need access to the type of the current class, and I'm currently cleaning up with this via a DRY-violating pattern:

struct ThisScruct{ int a; double b; //example static method using this - purely example - not full usecase static size_t sum_offsets(){ typedef ThisStruct SelfT; return offsetof(SelfT, a) + offsetof(SelfT, b); } }; 

This is due to the use of the offsetof , at least in my own work.

Now, before you close this without being accessible with the static method, make sure I just want to know how to get the ThisStruct type in a generic / macro friendly form from the context of the static method. I really don't need / need an instance, and I'm looking for a way that actually works, as mentioned above, without entering SelfT text.

Edit: something like this is being asked in. Can I implement a standalone self element type in C ++? - but I'm worried about the problem of forming a diamond with classes as inheriting from the accepted class of the answer self .

+9
source share
1 answer

You can use a CRT template to share typename, you just need to specify it in the inheritance list.

  template<class T> struct Type { using type = T; }; struct ThisScruct : Type<ThisStruct> { int a; double b; // this function can be copy-pasted into every // struct definition, which is inherited from // Type and contains the members a and b static size_t sum_offsets(){ typedef Type::type SelfT; return offsetof(SelfT, a) + offsetof(SelfT, b); } }; 

You can rename Type to a more friendly name. But you can consider completely replacing this functionality with a CRT template by moving functions to an inherited structure.

  template<class T> struct SumOffsets { static size_t sum_offsets(){ typedef T SelfT; return offsetof(SelfT, a) + offsetof(SelfT, b); } }; struct ThisStruct : SumOffsets<ThisStruct> { int a; double b; }; 

The sum_offsets function can be accessed through ThisStruct::sum_offsets , because even static functions are inherited. SumOffsets does not SumOffsets any additional costs, since neither virtual functions are involved nor SumOffsets have data members.

0
source

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


All Articles