Highlighting Member Pointer Pattern Arguments

Consider classes with member variables, for example:

struct A {
    int a;
    char b;
};

struct B {
    double c;
    bool d;
};

Is it possible to declare a template class that accepts a pointer-member-object argument as a template to any declared member in the above classes? A class that accepts a common member pointer object can be declared and used as follows:

template<typename Class, typename Type, Type (Class::*Member)>
struct Magic
{ };

// Usage:
typedef Magic<A, int, &A::a> MagicWithA_a;

Unfortunately, it is rather cumbersome to have to go into Classand Typethe template arguments each time to make the final pointer work.

Is there a way for these arguments to be deduced by partial specialization, for example? That is, how can you declare a class Magicto make lower definitions work?

typedef Magic<&B::c> MagicWithB_c;
typedef Magic<&A::b> MagicWithA_b;
+4
source share
2 answers

++ 17 auto :

template<auto p_member>
struct Magic
{ };

++ 17 , .

+6

, . , , . -, :

template<typename T, T pm>
struct MagicImpl; // Undefined for most types

, , :

template<class Class, typename Type>
struct MagicImpl<Type Class::*, Type (Class::*Member)> {
};

, , decltype, -, :

#define MAGIC(...) MagicImpl<decltype(__VA_ARGS__), __VA_ARGS__>

:

typedef MAGIC(&B::c) MagicWithB_c;
typedef MAGIC(&A::b) MagicWithA_b;
+3

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


All Articles