Automatically pick a variable type big enough to hold a specified number

后端 未结 14 2054
耶瑟儿~
耶瑟儿~ 2020-12-07 14:01

Is there any way in C++ define a type that is big enough to hold at most a specific number, presumably using some clever template code. For example I want to be able to writ

14条回答
  •  孤街浪徒
    2020-12-07 14:21

    #include 
    
    template
    struct RequiredBits
    {
        enum { value =
            Max <= 0xff       ?  8 :
            Max <= 0xffff     ? 16 :
            Max <= 0xffffffff ? 32 :
                                64
        };
    };
    
    template struct SelectInteger_;
    template<> struct SelectInteger_ <8> { typedef uint8_t type; };
    template<> struct SelectInteger_<16> { typedef uint16_t type; };
    template<> struct SelectInteger_<32> { typedef uint32_t type; };
    template<> struct SelectInteger_<64> { typedef uint64_t type; };
    
    template
    struct SelectInteger : SelectInteger_::value> {};
    
    int main()
    {
        SelectInteger<12345>::type x = 12345;
    }
    

提交回复
热议问题