vendredi 25 septembre 2020

Create a type trait that can be called both on types and on variables

There are two operators in C++ that can be called both on types and on variables: sizeof and typeid.

Suppose we want to implement our own operation with a similar behavior, something like*:

template<bool is_type>
struct type_traits_T;

template<>
struct type_traits_T<true> {
    template<typename T>
    struct type_traits {
        using mydecltype = T;
        // and other stuff...
    };
};

template<>
struct type_traits_T<false> {
    template<auto VAR>
    struct type_traits {
        using mydecltype = decltype(VAR);
        // and other stuff...
    };
};

This could have worked quite nicely, with a macro:

#define type_traits(V) type_traits_T<is_type(V)>::type_traits<V>

The missing part for the above is the is_type(V) part.

Is there a way to implement is_type(V) that would result with true in case V is a type, and false if V is a variable? If not, would there be a way to achieve that with the static reflection proposal?


* The use of a template to capture the variable has its own restrictions. It may be refactored by moving the call to decltype into the macro. However the question doesn't focus on the template part, which is here just for the purpose of having a simple and viable use case.





Aucun commentaire:

Enregistrer un commentaire