std::vector is known to meet the requirement of a RandomAccessContainer, so using the [] operator is constant time. However, std::list only meets the weaker requirements of a Container and ReversibleContainer, and hence retrieving an element is O(N), moreover the [] operator doesn't exist.
I would like to constrain a template so that I can get a nice compile-time error whenever the [] operator doesn't exist or is not O(1). How can I achieve this?
Currently, on g++ 11.2.0, I cannot get a clean error message when instantiating the following templates with a std::list:
template<typename RandomAccessContainer>
void foo(RandomAccessContainer const & x);
template<typename ContiguousContainer>
void foo(ContiguousContainer const & x);
template<typename T>
requires ContiguousContainer<T>
void foo(T const & x);