[英]C++ Choose template output type for input type
Consider I want to implement the following function: 考虑我要实现以下功能:
template<typename InputType, typename = typename std::enable_if<std::is_arithmetic<InputType>::value>::type>
inline InputType degreeToRadians(InputType degree)
{
return degree * (PI / 180.0);
}
How do I find the correct OutputType for the given InputType? 如何找到给定InputType的正确OutputType? Since the InputType could be some integral number the function would return a wrong result because the calculated number is casted to the integral InputType.
由于InputType可能是某个整数,因此该函数将返回错误的结果,因为计算出的数字将转换为整数InputType。 I have also considered to just return a long double (the largest floating point number I think) but it seems like a waste of memory.
我还考虑过只返回一个长整数(我认为是最大的浮点数),但这似乎浪费了内存。 What would you suggest to solve this problem?
您会提出什么解决方案? By the way I DON'T want to include template specifications whenever i call this function:
顺便说一句,我不想在每次调用此函数时都包含模板规范:
float someFloat = degreeToRadians<float>(someIntegral);
In C++11: 在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);
}
In C++14: 在C ++ 14中:
template<typename InputType,
typename = std::enable_if_t<std::is_arithmetic<InputType>::value>>
auto degreeToRadians(InputType degree)
{
return degree * (PI / 180.0);
}
BTW, you probably want to do the computaion with InputType
, I mean that PI
and 180
have type InputType
instead. 顺便说一句,您可能想使用
InputType
,我的意思是PI
和180
改为具有InputType
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.