Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deducing pointer-to-member template arguments

Tags:

c++

templates

Consider classes with member variables, like these:

struct A {
    int a;
    char b;
};

struct B {
    double c;
    bool d;
};

Is it possible to declare a template class that accepts as its template argument a pointer-to-member-object to any one of the members declared in the above classes? A class that accepts a generic pointer-to-member-object could 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 quite cumbersome having to pass in the Class and Type template arguments every time to make the final pointer work.

Is there any way to have these arguments deduced by partial specialization, for example? That is, how can the Magic class be declared to make the below definitions work?

typedef Magic<&B::c> MagicWithB_c;
typedef Magic<&A::b> MagicWithA_b;
like image 776
Kamajii Avatar asked Jan 02 '23 21:01

Kamajii


1 Answers

With C++17 you can use auto non-type template parameter:

template<auto p_member>
struct Magic
{ };

Before C++17 only the longer variant that you've implemented would work.

like image 129
user7860670 Avatar answered Jan 05 '23 16:01

user7860670