考虑我要实现以下功能:
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。我也考虑过只返回一个 long double (我认为最大的 float ),但这似乎是在浪费内存。你会建议什么来解决这个问题? 顺便说一句,我不想在调用此函数时包含模板规范:
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++ 为输入类型选择模板输出类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33043206/