Search code examples
c++templatestype-traitsstdarray

How to determine if strong type's base type is std::array<char, N> using only standard library


Want to extend base_is_char_array for any size character array.

Open to an entirely different solution than using is_base_of. But I am constrained to the standard library for reasons far outside my control.

Outside of something gross that iterates to a fixed maximum array size, I'm out of ideas.

#include <array>
#include <iostream>

template< class Derived > auto base_is_char_array(){
    return std::is_base_of<std::array<char, 10>, Derived>::value;
}

int main() {
    class tester : std::array<char, 10>{};
    std::cout << base_is_char_array<tester>() << std::endl;
    std::cout << base_is_char_array<int>() << std::endl;
}

Solution

  • cppreference gives a possible implementation of std::is_base_of. You can use the same technique to implement your base_is_char_array:

    namespace details {
        template <std::size_t N>
        std::true_type  test_ptr_convertible_to_char_array(const volatile std::array<char, N>*);
        std::false_type test_ptr_convertible_to_char_array(const volatile void*);
     
        template <typename>
        auto test_base_is_char_array(...) -> std::true_type;
        template <typename D>
        auto test_base_is_char_array(int) ->
            decltype(test_ptr_convertible_to_char_array(static_cast<D*>(nullptr)));
    }
     
    template <typename Derived>
    struct base_is_char_array :
        std::integral_constant<
            bool,
            std::is_class<Derived>::value &&
            decltype(details::test_base_is_char_array<Derived>(0))::value
        > { };