Determining the “optimal” common numeric type in a template parameter pack

后端 未结 3 571
清酒与你
清酒与你 2021-01-05 05:02

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, a
3条回答
  •  梦毁少年i
    2021-01-05 05:30

    I am a little bit late to the party, here is my solution without Boost:

    #include 
    #include 
      
    template struct mk_signed { typedef I       type; };
    template<>   struct mk_signed   { typedef int16_t type; };
    template<>   struct mk_signed   { typedef int32_t type; };
    template<>   struct mk_signed   { typedef int64_t type; };
    template<>   struct mk_signed   { typedef int64_t type; }; 
      
    template  struct best_common_numeric_type;
    template      struct best_common_numeric_type { typedef T type; };
      
    template 
    struct best_common_numeric_type {
       typedef typename best_common_numeric_type::type TS;     
       typedef typename std::conditional < (sizeof(T) > sizeof(TS)), T, TS>::type  bigger_integral;
       constexpr static bool fp = std::is_floating_point::value || std::is_floating_point::value;
       constexpr static bool have_signed = !fp && (std::is_signed::value || std::is_signed::value);
      
       typedef typename std::conditional <
         fp,
         typename std::common_type::type,
         typename mk_signed::type
       >::type type;
    };
    

提交回复
热议问题