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

后端 未结 14 2022
耶瑟儿~
耶瑟儿~ 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:19

    #define UINT8_T   256
    #define UINT16_T  65536
    #define UINT32_T  4294967296
    
    template
    struct UInt16_t { typedef uint16_t type; };
    template
    struct UInt16_t { typedef uint32_t type; };
    
    template
    struct UInt8_t { typedef uint8_t type; };
    template
    struct UInt8_t { typedef typename UInt16_t::type type; };
    
    template
    struct Integer {
      typedef typename UInt8_t::type type;
    };
    

    You can extend upto uint64_t or whatever your platform supports.

    Demo.

提交回复
热议问题