为输入类型选择模板输出类型

C++ Choose template output type for input type

本文关键字:类型 输出 选择 输入      更新时间:2023-10-16

考虑我想实现以下函数:

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来计算,我的意思是PI180的类型是InputType