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

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

    How about a conditional:

    #include 
    #include 
    
    template 
    struct MinInt
    {
      typedef typename std::conditional< N < std::numeric_limits::max(),
           unsigned char, std::conditional< N < std::numeric_limits::max(),
             unsigned short int>::type,
             void*>::type>::type
        type;
    };
    

    This would have to be extended to encompass all desired types, in order; at the final stage you could use enable_if rather than conditional to have an instantiation error right there if the value is too large.

提交回复
热议问题