Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

For instance:

template <typename Type1, typename Type2>
void fun(const Type1 &v1, const Type2 &v2)
{
    largest<Type1, Type2>::type val = v1 + v2;
    .
    .
    .
};

I'd like to know if there's a "largest" somewhere, perhaps in boost.

like image 639
chila Avatar asked Dec 23 '09 14:12

chila


3 Answers

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;
};
like image 51
Alexey Malistov Avatar answered Nov 09 '22 22:11

Alexey Malistov


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.

like image 30
Stephen Nutt Avatar answered Nov 09 '22 22:11

Stephen Nutt


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.

like image 28
wheaties Avatar answered Nov 09 '22 23:11

wheaties