简体   繁体   中英

Can C++11 deduce class type and member type from pointer-to-member template parameter

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.

eg 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.

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

ManuelAtWorks' answer appears the best option for C++11.

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)>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM