c++ - 在模板函数中确定忠实表示整数类型参数的最短浮点类型
问题描述
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
.
这在没有专业化的情况下可行吗?
解决方案
事实上,这在不直接使用专业化的情况下是可能的。您可以使用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.
...
}
推荐阅读
- python - 使用 GCC for Python 构建 GPU 卸载 C++ 库的链接错误
- java - 串行通信 RXTX 和 Arduino 的问题
- regex - 正则表达式 - 条件后视,过滤器开始?
- javascript - 使用 node js 在后端尝试配置文件路由,而不使用 passport.js 进行身份验证
- java - Spring Data Test ExpectedException - 没有抛出异常
- python - 根据两列合并熊猫中的两个数据框
- javascript - 性能问题 - React Hooks useEffect
- azure - 错误:无法获取资源类型“Microsoft.Web/Sites”的资源 ID
- python - 导入 UTF-8 文本文件(并在数据框中输入)
- kotlin - listOf Kotlin 返回的对象类型