[英]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
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.