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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With