mercredi 6 décembre 2023

How to Extend C++ Type Traits to Support Pointers and References?

I'm working on a type traits class in C++ and need some assistance in extending its functionality to cover pointers and references. Currently, my class provides traits to check if a type is derived from another, if it's a class or struct, and if it's a primitive or integer type. However, it fails when dealing with pointers or references, as it only considers the direct type.

Here is the existing implementation:

template <typename Derived, typename Base>
using is_derived_from = std::is_base_of<Base, Derived>;

template <typename Type>
using is_class = std::is_class<Type>;

template <typename primitiveT>
using is_primitive = std::integral_constant<bool,
    std::is_floating_point<primitiveT>::value ||
    std::is_integral<primitiveT>::value>;

template <typename TypeInt>
using is_integer = std::integral_constant<bool,
    std::is_integral<TypeInt>::value && !std::is_same<TypeInt, bool>::value>;

template <typename Type, typename Expected>
using is_valid_type = std::integral_constant<bool,
    (is_primitive<Type>::value && std::is_same<Type, Expected>::value) ||
    (is_class<Type>::value && is_derived_from<Type, Expected>::value)
>;

I want to modify is_valid_type to also correctly handle pointers and references. For example, if Type is a pointer or reference to a class derived from Expected, or a pointer/reference to a primitive type that matches Expected, it should still be considered valid.

I've considered using std::remove_pointer and std::remove_reference, but I'm unsure how to integrate them effectively without complicating the code too much.

Any suggestions on how to modify is_valid_type or the approach in general to handle pointers and references efficiently and elegantly in C++?

Aucun commentaire:

Enregistrer un commentaire