oel_runs_the_world
oel_runs_the_world

Reputation: 103

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);

Upvotes: 0

Views: 1271

Answers (1)

Jarod42
Jarod42

Reputation: 217265

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.

Upvotes: 1

Related Questions