在标准中是否有这样的模板函数的“工具”:
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_tstd::uint16_t -> std::uintmax_tfloat -> long double (或其他类型,由实现决定)当然,我可以自己写,但是在标准中有这样的东西会很好。
编辑:
我可以使用移动平均,但是这个函数只用于少量的参数(通常是2-8),但是我使用的类型很容易“溢出”。
编辑2:
我也知道,对于较大数量的参数,最好使用任何类型的数组。
发布于 2018-02-23 02:21:57
使用最宽的类型并不保证没有溢出(并且在除法时仍然可以删除小数值),但是您可以扩展提升规则以完成以下操作:
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。
https://stackoverflow.com/questions/48939956
复制相似问题