• Adam Langley's avatar
    base: add EXTENT macro. · c43f927a
    Adam Langley authored
    It's annoying that one cannot just call size() on a std::array in a
    compile-time context. Instead std::tuple_size and std::remove_reference
    is needed. While std::array is used quite a lot in Chromium,
    std::tuple_size is not. I assume that people are either not writing
    assertions, using run-time [D]CHECKs, or using static_assert with
    constants that are also used as std::array lengths.
    
    None the less, I cannot point at a body of std::tuple_size in the code
    base that would be cleaned up by this, so the case for adding a #define
    is not that strong. *I* would certainly use it in static_asserts though!
    (And would change [D]CHECKs into static asserts.) Maybe others would
    too.
    
    A #define isn't as nice as a constexpr function, but the latter doesn't
    work as nicely at the call site. Consider the obvious:
    
      template<typename T, size_t N> constexpr size_t std_array_size(const std::array<T, N>&) { return N; }
    
    That works, but not for references, where the compiler objects that the
    reference “is not a constant expression”, even though the value is never
    used.
    
    Other non-define functions can work if preferred, but are worse at the
    callsite. For example:
    
      template<typename T> constexpr size_t std_array_size() {
        return std::tuple_size<typename std::remove_reference<T>::type>::value;
      }
    
    But that has the callsite pattern:
    
      static_assert(base::std_array_size<decltype(array)>() == kFoo);
    
    This this change uses base::span::extent to define a macro, EXTENT, that
    works for any type that base::make_span recognises, including
    std::array.
    
    Change-Id: Id4688117b5a558e022448ad901fa3d4995182826
    Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2364136Reviewed-by: default avatarJan Wilken Dörrie <jdoerrie@chromium.org>
    Commit-Queue: Adam Langley <agl@chromium.org>
    Cr-Commit-Position: refs/heads/master@{#801142}
    c43f927a
span.h 17.6 KB