Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 800
Arjonais Avatar asked Oct 25 '25 14:10

Arjonais


2 Answers

[...] 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

like image 97
JeJo Avatar answered Oct 27 '25 03:10

JeJo


It is much simpler than previous answers. Just test each type you want to support:

template <typename T, size_t N>
concept fixed_container = std::ranges::sized_range<T> &&
                        ( std::extent_v<T> == N || // var[N]
                          T::extent == N || // std::span
                          std::tuple_size<T>::value == N ); // Tuple-like types, i.e. std::array
like image 32
Arjonais Avatar answered Oct 27 '25 02:10

Arjonais



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!