与给定类型相似的最广泛可能类型 - C++

Widest possible type similar to a given one - C++

标准中有没有"tool",对于这样的模板函数:

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 来形象化用法。平均计算需要对每个参数求和,因此,为了避免(或尽可能减少)溢出,我需要尽可能使用最大宽度类型。示例:

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

编辑:
我可以使用 moving average,但是这个函数只会用于少量参数(通常为 2-8 个),但我使用的类型很容易 "overflowable".
编辑 2:
我也知道,对于更大数量的参数,最好使用任何类型的数组。

使用最宽的类型并不能保证不溢出(并且在除法时仍然可以去掉小数值),但是你可以扩展提升规则来做到这一点:

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.