At compile time in C++11 in a template function that takes 2 template parameters, both of which must be unsigned integer types, I'd like to have a local variable have the type of whichever of the two template parameters has more bits. In C++03 I might write something like:
template<bool, class T, class U>
struct pick_first;
template<class T, class U>
struct pick_first<true, T, U> {
typedef T type;
};
template<class T, class U>
struct pick_first<false, T, U> {
typedef U type;
};
template<class T, class U>
struct pick_bigger {
typedef typename pick_first<(sizeof(T) >= sizeof(U)), T, U>::type type;
};
// usage
template<class uintX_t, class uintY_t>
void foo() {
typename pick_bigger<uintX_t, uintY_t>::type mylocal = 0;
// insert doing stuff with mylocal here
}
Can I leverage any of the new C++11 features to make this simpler? I know I could use variadic templates to make it work with more than just pairs of types, and instead of using pick_first I could write lots of specializations to make it work with the new int_leastX_t and int_fastX_t types. But I'm curious if there's just a plain better approach to this. Maybe somehow leveraging auto/constexpr/decltype?
std::common_type
– Sayerscommon_type
will not always work due to integer promotion rules. For instance,std::common_type<short,char>::type
isint
, which may be larger than either of the 2 types. – Pirnpick_first
template seems to be aptly named. – Interrogation