首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尽可能宽的类型,类似于给定的类型- C++

尽可能宽的类型,类似于给定的类型- C++
EN

Stack Overflow用户
提问于 2018-02-23 01:48:43
回答 1查看 93关注 0票数 0

在标准中是否有这样的模板函数的“工具”:

代码语言:javascript
复制
template<typename FirstArg, typename... Args>
auto average(FirstArg &&firstArg_, Args&&... args_)
{
    // example:
    std::widest_type_t<FirstArg> sum;
    sum += std::forward<FirstArg>(firstArg_);
    sum += (... + std::forward<Args>(args_)); // unfold
    sum /= (sizeof...(Args) + 1);
    return sum;
}

让我们说,这个模板中的每个参数类型都是相同的。例如:n个std::int32_t的平均值。我使用虚构的widest_type_t来可视化使用情况。因此,为了避免(或尽可能地最小化)溢出,平均计算需要对每个参数进行加和。我需要使用最大宽度类型。例如:

  • char -> std::intmax_t
  • std::uint16_t -> std::uintmax_t
  • float -> long double (或其他类型,由实现决定)

当然,我可以自己写,但是在标准中有这样的东西会很好。

编辑:

我可以使用移动平均,但是这个函数只用于少量的参数(通常是2-8),但是我使用的类型很容易“溢出”。

编辑2:

我也知道,对于较大数量的参数,最好使用任何类型的数组。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-23 02:21:57

使用最宽的类型并不保证没有溢出(并且在除法时仍然可以删除小数值),但是您可以扩展提升规则以完成以下操作:

代码语言:javascript
复制
template<typename T>
struct widest_type {
    static constexpr auto calculate() {
        if constexpr (std::is_floating_point_v<T>) {
            using LongDouble = long double;
            return LongDouble{};
        } else if constexpr (std::is_signed_v<T>) {
            return std::intmax_t{};
        } else if constexpr (std::is_unsigned_v<T>) {
            return std::uintmax_t{};
        } else {
            return std::declval<T>();
        }
    }

    using type = decltype(calculate());
};

template<typename T>
using widest_type_t = typename widest_type<T>::type;

template<typename FirstArg, typename... Args>
auto average(FirstArg &&firstArg_, Args&&... args_)
{
    using Common = std::common_type_t<FirstArg, Args...>;
    widest_type_t<Common> sum;
    sum += std::forward<FirstArg>(firstArg_);
    sum += (... + std::forward<Args>(args_)); // unfold
    sum /= sizeof...(args_) + 1;
    return sum;
}

如果if constexpr不可用,那么std::conditional就能做到这一点。同样,std::is_foo<T>{}代替了std::is_foo_v<T>

我选择将类型特征限制在单个类型上,因为std::common_type已经做了合理的工作,解决了如何组合类型。您会注意到我使用它,并将结果传递给widest_type

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48939956

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档