写了一些容器类,我迫切希望避免将size_t用于容量和迭代,以仅涵盖每种情况。假设我只需要一个50大小的东西,一个无符号的char就可以。但是如何从给定的所需容量中模板化此类型?是否有任何类型特征?
template<class T, size_t capacity> MyBuffer{
...
using IDX = intRequired<capacity>; // desired
...
T & At(IDX at);
IDX Lenght();
}
标准中没有这样的类型特征,但是您可以自己做类似的事情:
#include <cstdint>
#include <limits>
#include <type_traits>
template <auto capacity, typename... intTypes>
struct intRequiredImpl;
template <auto capacity, typename intType>
struct intRequiredImpl<capacity, intType> {
using type = intType;
// avoid overflow
static_assert(capacity <= std::numeric_limits<type>::max(),
"Largest specified type is not capable of holding the capacity.");
};
template <auto capacity, typename SmallInt, typename... LargeInts>
struct intRequiredImpl <capacity, SmallInt, LargeInts...> {
using type = std::conditional_t <
(capacity <= std::numeric_limits<SmallInt>::max()),
SmallInt, typename intRequiredImpl<capacity, LargeInts...>::type>;
};
template <auto capacity>
using uintRequired = typename intRequiredImpl<capacity,
std::uint8_t,
std::uint16_t,
std::uint32_t,
std::uint64_t>::type;
int main() {
uintRequired<50> i; // std::uint8_t
}
得到了一些帮助,最终得到了这个:
template<size_t Max>
using BestFitUint = std::conditional_t < Max <= UINT8_MAX, uint8_t,
std::conditional_t < Max <= UINT16_MAX, uint16_t,
std::conditional_t< Max <= UINT32_MAX, uint32_t,
std::uint64_t > > >;
效果很好,不确定与Ayxan的答案有何不同。