是否有任何类型特征方法可以从所需的范围容量中获取int类型?

问题描述 投票:0回答:2

写了一些容器类,我迫切希望避免将size_t用于容量和迭代,以仅涵盖每种情况。假设我只需要一个50大小的东西,一个无符号的char就可以。但是如何从给定的所需容量中模板化此类型?是否有任何类型特征?

template<class T, size_t capacity> MyBuffer{
 ...
 using IDX = intRequired<capacity>; // desired
 ...
 T & At(IDX at);
 IDX Lenght();

}
c++ templates metaprogramming typetraits
2个回答
3
投票

标准中没有这样的类型特征,但是您可以自己做类似的事情:

#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
}

0
投票

得到了一些帮助,最终得到了这个:

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的答案有何不同。

© www.soinside.com 2019 - 2024. All rights reserved.