Friday, 16 August 2013

determining the "optimal" common numeric type in a template parameter pack

determining the "optimal" common numeric type in a template parameter pack

What is the best way to determine a common numeric type in a template
parameter pack with 1) the smallest size, 2) no loss of precision, and 3)
no risk of overflow/underflow when converting any type in the parameter
pack to this "ideal" common type?
The variadic template (best_common_numeric_type) could be used like so:
template<typename... NumericTypes>
auto some_numeric_func(const NumericTypes&...)
-> typename best_common_numeric_type<NumericTypes...>::type;
And have instantiations like the following:
[1] best_common_numeric_type<long, unsigned long, float, double,
int>::type = double
[2] best_common_numeric_type<unsigned int, unsigned long>::type = unsigned
long
[3] best_common_numeric_type<signed int, signed long>::type = signed long
[4] best_common_numeric_type<signed int, unsigned int>::type = signed long
[5] best_common_numeric_type<signed int, unsigned long>::type = int128_t
(maybe)
So in case [4] for example, ::type would have to be signed long, since
signed int could not hold an unsigned int without risk of overflow, and
conversely unsigned int could not hold a signed int without risk of
underflow.
The same applies in [5], except now a signed long is no longer sufficient
since it could not hold the unsigned long without risk of overflow.
(The implementation might be data model specific, but you get the idea.)
So what might be the best way in C++11 to achieve this? Thanks

No comments:

Post a Comment