Search code examples
c++templatescontainersc++20c++-concepts

How to check template parameter is a container of fixed length using concept?


I would like to have a concept that checks if a type is a container of fixed length. The type could be a C-style array, a std::array, a std::span or a custom-made container. I can check for the container condition as shown in the code below, but I cannot get it to check for the length condition.

template <typename T, size_t N>
concept fixed_container =
   requires (T const& t)
   {
       {std::size(t)} -> std::same_as<size_t>;
       {std::begin(t)};
       {std::end(t)};
   }
   // && std::declval<T>().size() == N // Error: 'declval() must not be used!'
   // && T::size() == N // Error: 'call to non-static member function without an object argument'
   ;

// These should all be correct
static_assert( fixed_container<std::array<double, 3>, 3>);
static_assert(!fixed_container<std::array<double, 3>, 4>);
static_assert( fixed_container<std::span<double, 3>,  3>);
static_assert(!fixed_container<std::span<double, 3>,  4>);
static_assert( fixed_container<double[3],             3>);
static_assert(!fixed_container<double[3],             4>);

Any ideas?

EDIT: The block

   requires (T const& t)
   {
       {std::size(t)} -> std::same_as<size_t>;
       {std::begin(t)};
       {std::end(t)};
   }

can be replaced by a single line

   std::ranges::sized_range<T>

Solution

  • [...] but I cannot get it to check for the length condition.

    You'll need to handle it separately. For example, you might do the following (Which is inspired by a similar question mentioned in the comments):

    template<typename T>
    constexpr std::size_t get_fixed_size()
    {
       if constexpr (std::is_array_v<T>)            return std::extent_v<T>;
       else if constexpr (requires { T::extent; })  return T::extent; // For std::span
       else if constexpr (requires { std::tuple_size<T>::value; })  
             return std::tuple_size<T>::value;   // For std::array
       else  return 0;
    }
    
    template<typename T, std::size_t N>
    concept fixed_container = requires(T const& t)
    {
       { std::size(t) } -> std::same_as<std::size_t>;
       { std::begin(t) };
       { std::end(t) };
    }
    && get_fixed_size<std::remove_cvref_t<T>>() == N;
    

    See live demo