Select an integer type based on template integer parameter

前端 未结 6 1712
予麋鹿
予麋鹿 2020-12-16 16:15

I would like to create a class template which takes an unsigned integer parameter and has a member u_ whose type is the smallest unsigned integer type that will

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 16:37

    template
    struct A;
    
    template<>
    struct A<0>{
        enum {id = 0};
        using type = uint8_t;
    };
    
    template<>
    struct A<255>{
        enum {id = 255};
        using type = uint8_t;
    };
    
    template<>
    struct A<256>{
        enum {id = 256};
        using type = uint16_t;
    };
    
    int main(){
        typename A<255>::type a0 = 255; // uint8_t
        typename A<256>::type a1 = 256; // uint16_t
    }
    

    But I think you want to have a class so that every value under 256 will define uint8_t, every value under 65536 will define uint16_t etc. etc.

    So just incase, this is how you would do that:

    template
    struct A{
        enum {value = Value};
        using type = std::conditional_t<
            (Value <= std::numeric_limits::max()), uint8_t,
                std::conditional_t<
                    (Value <= std::numeric_limits::max()), uint16_t,
                        std::conditional_t<
                            (Value <= std::numeric_limits::max()), uint32_t
                                std::conditional_t<
                                    (Value <= std::numeric_limits::max()), uint64_t, uintmax_t
                                >
                        >
                >
        >;
    };
    

    And here's a live example

提交回复
热议问题