首页 > 解决方案 > 在模板函数中确定忠实表示整数类型参数的最短浮点类型

问题描述

template< typename int_type >
bool foo( int_type argument )
{
    float_type value = argument; // float_type must faithfully represent argument.
    ...
}

也就是说,我想在模板函数中派生最短的浮点类型float_type,它的有效数字至少与模板参数一样多int_type

foo<int16>应该使用float.

foo<int32>应该使用double.

foo<int64>应该使用long double.

这在没有专业化的情况下可行吗?

标签: c++c++11templatestypes

解决方案


事实上,这在不直接使用专业化的情况下是可能的。您可以使用std::conditional标准标头type_traits根据以下大小有条件地定义类型int_type

template< typename int_type >
bool foo(int_type argument)
{
    using float_type = std::conditional<sizeof(int_type) <= 4,
                                        std::conditional<sizeof(int_type) == 4, double, float>::type,
                                        long double>::type;
    float_type value = argument; // float_type must faithfully represent argument.
    ...
}

推荐阅读