简体   繁体   中英

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? 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. 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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM