[英]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.文档说,
std::vector
的size_type
是 /通常/ size_t
,这是合理的,因为实现可以选择使用不同的。
But why is size_type = size_t
in std::array
.但是为什么
std::array
中的size_type = size_t
。 Especially here, as std::array
is used on small µC
a lot, it would be better to let the implemenatation have some freedom.尤其是在这里,由于
std::array
经常在小型µC
上使用,所以最好让实现有一些自由度。
Is this a doc-defect?这是文档缺陷吗?
It's defined to be that way because size_t
is defined to be sufficient for all arrays.之所以这样定义,是因为
size_t
被定义为足以满足所有 arrays 的要求。 If you want a smaller type for smaller arrays, you can always narrow when appropriate based on constexpr
values.如果您想要更小的 arrays 的类型,您可以随时根据
constexpr
值缩小范围。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.