Search code examples
c++stdarray

What is the purpose of `std::tuple_size<std::array>`


I have two questions concerning the helper class std::tuple_size<std::array> of std::array.

First, there is a constexpr size() member function in class std::array, why does one need std::tuple_size<std::array>?

Second, is the name tuple_size misleading?


Solution

  • The design goal of std::tuple_size (and its friends std::tuple_element and std::get) is to work not only on literal std::tuples, but on anything tuple-like. Something being tuple-like generally just means that it is a compound type containing a fixed number of ordered elements.

    You can clearly see this abstraction in use by looking, for example, at how structured bindings are defined : they allow decomposing anything that has sensible implementations of std::tuple_size, std::tuple_element and get<I>.

    Under this broadened notion of "tuple-like", it only makes sense that std::array (and std::pair) would specialize these traits to be handled as a tuple of N identical types (resp. a tuple of size 2).