gpt4 book ai didi

c++ - 判断模板参数包中 "optimal"公共(public)数值类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:53:34 28 4
gpt4 key购买 nike

在模板参数包中确定常见数字类型的最佳方法是:

  1. 最小尺寸,
  2. 没有精度损失,并且
  3. 将参数包中的任何类型转换为这种“理想”通用类型时没有上溢/下溢的风险吗?

可变参数模板(best_common_numeric_type)可以像这样使用:

template<typename... NumericTypes>
auto some_numeric_func(const NumericTypes&...)
-> typename best_common_numeric_type<NumericTypes...>::type;

并有像下面这样的实例化:

[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)

例如,在案例 [4] 中,::type 必须是 signed long,因为 signed int 不能保存一个unsigned int 没有溢出的风险,相反,unsigned int 不能容纳 signed int 而没有下溢的风险。

这同样适用于 [5],除了现在 signed long 不再足够,因为它不能容纳 unsigned long 而没有溢出的风险。

(实现可能是 data model 具体的,但您明白了。)

那么在 C++11 中实现这一目标的最佳方法是什么?

最佳答案

我来晚了一点,这是我没有提升的解决方案:

#include <type_traits>
#include <cstdint>
  
template<class I, bool Signed> struct mk_signed { typedef I       type; };
template<>   struct mk_signed<uint8_t , true>   { typedef int16_t type; };
template<>   struct mk_signed<uint16_t, true>   { typedef int32_t type; };
template<>   struct mk_signed<uint32_t, true>   { typedef int64_t type; };
template<>   struct mk_signed<uint64_t, true>   { typedef int64_t type; };
  
template <typename... Ts> struct best_common_numeric_type;
template <typename T>     struct best_common_numeric_type<T> { typedef T type; };
  
template <typename T, typename... Ts>
struct best_common_numeric_type<T, Ts...> {
   typedef typename best_common_numeric_type<Ts...>::type TS;   
   typedef typename std::conditional < (sizeof(T) > sizeof(TS)), T, TS>::type  bigger_integral;
   constexpr static bool fp = std::is_floating_point<T>::value || std::is_floating_point<TS>::value;
   constexpr static bool have_signed = !fp && (std::is_signed<T>::value || std::is_signed<TS>::value);
  
   typedef typename std::conditional <
     fp,
     typename std::common_type<T,TS>::type,
     typename mk_signed<bigger_integral,have_signed>::type
   >::type type;
};

关于c++ - 判断模板参数包中 "optimal"公共(public)数值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23870123/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com