【发布时间】:2020-12-28 15:14:42
【问题描述】:
推导出浮点和复杂类型的最高精度类型,即
-
float/double/long double导致long double, -
std::complex<T>导致std::complex<long double>,
我的尝试 (live example on Wandbox) 感觉很笨拙:
#include <complex>
#include <type_traits>
template <typename T>
struct is_complex : std::false_type {};
template <std::floating_point T>
struct is_complex<std::complex<T>> : std::true_type {};
template <typename T>
inline constexpr bool is_complex_v = is_complex<T>::value;
template <typename T>
struct highest_precision_type
{
// none for arbitrary type
};
template <typename T>
requires std::is_floating_point_v<T>
struct highest_precision_type<T>
{
typedef long double type;
};
template <typename T>
requires is_complex_v<T>
struct highest_precision_type<T>
{
typedef std::complex<long double> type;
};
int main()
{
auto f = highest_precision_type<float>::type{1};
auto cf = highest_precision_type<std::complex<float>>::type{0, 1};
static_assert(std::is_same_v<decltype(f), long double> );
static_assert(std::is_same_v<decltype(cf), std::complex<long double>> );
}
有没有更简洁的方法来达到预期的效果?
【问题讨论】:
-
IIRC、
long double和std::complex<long double>保证始终是最高精度。 -
@NathanOliver:同意。
highest_precision_type<T>旨在用于模板代码中,以将中间值提升到这些最高精度类型,以减少舍入和取消错误。 -
@RenéRichter 对于您的目标,这对我来说似乎是合理的。感觉笨拙?好吧,C++ 元编程非常笨拙。
-
除非你可以
template<typename T> struct highest_precision_type<std::complex<T>> { ...}你的代码看起来很棒。好吧,所以,你需要定义如何衡量“简洁性”以及如何准确减少代码的“笨拙感”,否则你的问题只是基于意见。