mercredi 29 septembre 2021

Macro for detecting non-static non-type members in classes

In C++ Templates - The complete guide, 2nd edition, at page 434, a macro is defined to generate predicates testing the existence of a nontype memeber in a class:

#include <type_traits>

#define DEFINE_HAS_MEMBER(Member)                    \
    template<typename T, typename = void>            \
    struct HasMemberT_##Member : std::false_type {}; \
    template<typename T>                             \
    struct HasMemberT_##Member<T, std::void_t<decltype(&T::Member)>> : std::true_type {};

The the text reads

It would not be difficult to modify the partial specialization to exclude cases wehre &T::Member is not a pointer-to-member type (which amounts to excluding static data members).

So I've played around with static_asserts and compiler errors and remember about types of static and non-static of members of classes:

struct A {
    int begin;
    static int end;
};
static_assert(std::is_same<decltype(&A::begin), decltype(A::begin) A::*>::value, ""); // passes
static_assert(std::is_same<decltype(&A::end), decltype(A::end)*>::value, "");         // passes

And thought that maybe a good modification of the lambda above aimed at detecting non-static members only is to change

: std::true_type

to

std::is_same<decltype(&T::Member), decltype(T::Member) T::*>

whereas if I wanted to check for static memebers only, I could change it to

std::is_same<decltype(&T::Member), decltype(T::Member)*>

Is it really this easy? Or am I overlooking something important?





Aucun commentaire:

Enregistrer un commentaire