简体   繁体   中英

Why is size_type in std::array size_t and in std::vector usually size_t?

The documentation says, that size_type of std::vector is /usually/ size_t , which is reasonable, since an implementation can choose to use different.

But why is size_type = size_t in std::array . Especially here, as std::array is used on small µC a lot, it would be better to let the implemenatation have some freedom.

Is this a doc-defect?

It's defined to be that way because size_t is defined to be sufficient for all arrays. If you want a smaller type for smaller arrays, you can always narrow when appropriate based on constexpr values.

template <typename Array>
struct small_array_size
{
    using type = size_t
};

template <typename T, size_t N, typename = std::enable_if_t<N < 256>>
struct small_array_size<std::array<T, N>>
{
    using type = uint8_t;
};

template <typename T, size_t N, typename = std::enable_if_t<N < 65536>>
struct small_array_size<std::array<T, N>>
{
    using type = uint16_t;
};

template <typename Array>
using small_array_size_t = typename small_array_size<Array>::type;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM