How can I find the largest (in size) of two integer types?

前端 未结 5 1535
独厮守ぢ
独厮守ぢ 2021-02-09 18:02

For instance:

template 
void fun(const Type1 &v1, const Type2 &v2)
{
    largest::type val          


        
相关标签:
5条回答
  • 2021-02-09 18:18

    There is no simple answer. If the largest type on your machine is a long and the two types passed are an unsigned long and a signed long, what type would you expect val to be? If unsigned you run the risk of a negative number which will not fit in it. If signed, you may overflow but still have a number that would fit in the unsigned number space.

    If these limitations are acceptable you could use Alexey Malistov's approach, but the resulting type if Type1 and Type2 are the same size but different types will be different depending on the order the values are passed.

    Take a look at the boost mpl function if_, with which you can pick one of two types. You'll need need to come up with your own rules for how to pick the resulting type.

    0 讨论(0)
  • 2021-02-09 18:22
    template<bool, typename T1, typename T2>
    struct is_cond {
        typedef T1 type;
    };
    
    template<typename T1, typename T2>
    struct is_cond<false, T1, T2> {
        typedef T2 type;
    };
    
    template<typename T1, typename T2>
    struct largest {
         typedef typename is_cond< (sizeof(T1)>sizeof(T2)), T1, T2>::type type;
    };
    
    0 讨论(0)
  • 2021-02-09 18:28

    You probably could roll your own with sizeof.

    http://www.cppreference.com/wiki/keywords/sizeof

    0 讨论(0)
  • 2021-02-09 18:33

    This won't be very feasible. How do you tell the difference between unsigned int and int? You can't use sizeof() because they're both the same "size" in the memory. I think you'll have to roll your own template specialization to handle those cases at which point I'd suggest just using an overloaded function.

    0 讨论(0)
  • 2021-02-09 18:35

    You can use the sizeof built-in function of c to get the memory size of the type. You can also call it on an instance of a type. For example:

    return (sizeof(v1) > sizeof(v2));

    0 讨论(0)
提交回复
热议问题