为输入类型选择模板输出类型
C++ Choose template output type for input type
考虑我想实现以下函数:
template<typename InputType, typename = typename std::enable_if<std::is_arithmetic<InputType>::value>::type>
inline InputType degreeToRadians(InputType degree)
{
return degree * (PI / 180.0);
}
如何为给定的InputType找到正确的OutputType ?由于InputType可以是某个整数,因此函数将返回错误的结果,因为计算的数字被强制转换为整数InputType。我也考虑过只返回一个长双精度(我认为最大的浮点数),但这似乎是浪费内存。你有什么建议来解决这个问题?顺便说一下,当我调用这个函数时,我不想包含模板规范:
float someFloat = degreeToRadians<float>(someIntegral);
c++ 11:
template<typename InputType,
typename = typename std::enable_if<std::is_arithmetic<InputType>::value>::type>
auto degreeToRadians(InputType degree)
-> decltype(degree * (PI / 180.0))
{
return degree * (PI / 180.0);
}
在c++ 14: template<typename InputType,
typename = std::enable_if_t<std::is_arithmetic<InputType>::value>>
auto degreeToRadians(InputType degree)
{
return degree * (PI / 180.0);
}
顺便说一句,你可能想用InputType
来计算,我的意思是PI
和180
的类型是InputType
。
相关文章:
- 在 C++ 中输出枚举类类型的向量元素
- 为什么在这种情况下,bool 类型的输出等于 0?
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- 无法在 HEVC 解码器上设置输出类型 IMFTransform
- 我的代码中是否有任何类型的错误,因为它没有给出正确的输出
- 来自 decltype 的意外输出类型
- 输出一个数字,该数字可能是三种类型之一
- 输出 [left]=input[i] 行中的 c++ 代码中存在无效的类型错误
- 为什么给我输出 2 我使用类型转换?
- GNU Radio中基于条件的输出的块类型
- 如何在编译过程中输出C 类型信息
- SSE和iostream:浮点类型的错误输出
- C 尝试使用模板输出功能来显示不同类型的数据
- 如果我获得Integer和Double的产品,输出的数据类型是什么
- 为什么没有"int"类型声明时输出不同?
- 如何将预定义数据类型的值存储到数组中并输出它
- 具有特征类型输出的特征二进制 Expr
- 双变量类型输出始终为 0
- 正在将自定义数据类型输出到文件