Home > front end >  Can C 11 deduce class type and member type from pointer-to-member template parameter
Can C 11 deduce class type and member type from pointer-to-member template parameter

Time:07-29

I'd like to make a traits class to deduce the class and member types from the pointer to a class member -- a single template parameter.

e.g. given

struct Example { int val; };

, I want a class

pointer_member<&Example::val>

with type definitions class_type=Example, member_type=int and the pointer-to-member itself.

I know c 17 can do this with template <auto>, but I'm stuck with c 11.

I know I could explicitly specify the class and member typenames preceding the pointer-to-member parameter. I hate redundancy. The compiler should know everything from &Example::val.

I know I could create a template function having template parameters <typename class_type,typename member_type> deduced by calling with a function argument member_type class_type::*ptr_to_mem. I'd even be willing to use the decltype() of such a call. Unfortunately, I need to access the specific member ptr_to_mem as a template parameter, not (just) as a passed argument. I cannot see how.

CodePudding user response:

The Motivation and Scope of P0127r1 suggest this is not possible with C 11.

ManuelAtWorks' answer appears the best option for C 11.

CodePudding user response:

In c 17, template <auto value> which allows pointer_member<&Example::val> usage.

For previous version, there are workaround, such as template <typename T, T value> with usage changed to pointer_member<decltype(&Example::val), &Example::val> MACRO can simplify usage a little:

#define AUTO(value) decltype(value), value

and then

pointer_member<AUTO(&Example::val)>
  • Related