jeudi 29 juillet 2021

Type trait to determine a data member's access specifier from a pointer-to-member to that member

I'm looking for a type trait that will allow me to find out if a pointer-to-member points to a public data member or not.

Example :

template<auto ptr>
struct is_public_member_ptr 
{
    // Possible?
};

class foo 
{
public:
    int i;
private:
    int j;

    static_assert(is_public_member_ptr<&foo::i>::value == true);
    static_assert(is_public_member_ptr<&foo::j>::value == false);
};

At first I considered using SFINAE to try and dereference the pointer-to-member and see if it worked, expecting substitution to fail for pointers to private members. Obviously that didn't work, you could only check if you are able to get the pointer-to-member in the first place. Once you have it, dereferencing will always succeed, even for private members.

This leads me to believe that there is no way to check the access specifier strictly from a pointer-to-member. That information isn't encoded into the pointer-to-member. But, it is possible to recover the original class to which the pointed member is a member of. So maybe there is some trick I missed.

Is this type trait achievable?

An ideal solution would be compatible with C++14, but solutions for any C++ version are fine too.





Aucun commentaire:

Enregistrer un commentaire