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

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

    Sure, it's possible. Here are the ingredients. Let's start with my two favorite meta-functions:

    template
    struct constant
    {
        enum { value = N };
    };
    
    template
    struct return_
    {
        typedef T type;
    };
    

    Then, a meta-function that counts the bits required to store a number:

    template
    struct bitcount : constant<1 + bitcount<(N>>1)>::value> {};
    
    template<>
    struct bitcount<0> : constant<1> {};
    
    template<>
    struct bitcount<1> : constant<1> {};
    

    Then, a meta-function that counts the bytes:

    template
    struct bytecount : constant<((bitcount::value + 7) >> 3)> {};
    

    Then, a meta-function that returns the smallest type for a given number of bytes:

    template
    struct bytetype : return_ {};
    
    template<>
    struct bytetype<4> : return_ {};
    
    template<>
    struct bytetype<3> : return_ {};
    
    template<>
    struct bytetype<2> : return_ {};
    
    template<>
    struct bytetype<1> : return_ {};
    

    And finally, the meta-function that you asked for:

    template
    struct Integer : bytetype::value> {};
    

提交回复
热议问题