Reputation: 38
I just had a basic question. Is this possible to simplify any further, because I call this same thing pretty much for a sin cos tan asin acos and atan. It just looks ugly and I want to make it look pretty if possible.
if(m_RHS->get_gType() == INT)
{
ostringstream ss;
ss << (sin(m_RHS->evalint() * (M_PI / 180)));
return ss.str();
}
else
{
ostringstream ss;
ss << (sin(m_RHS->evaldouble() * (M_PI / 180)));
return ss.str();
}
Upvotes: 1
Views: 522
Reputation: 29658
Yes, try this:
ostringstream ss;
double val;
if (m_RHS->get_gType() == INT){
val = m_RHS->evalint();
} else {
val = m_RHS->evaldouble();
}
ss << sin(val * (M_PI / 180));
return ss.str();
Notice that I used a double
as the type for val, because you can store an integer in a double, but not the other way around (without truncating).
Or for compactness (but sacrificing readability):
ostringstream ss;
ss << sin((m_RHS->get_gType() == INT ? m_RHS->evalint() : m_RHS->evaldouble()) * (M_PI / 180));
return ss.str();
Upvotes: 1
Reputation: 42805
Metaprogramming, fo' shizzle:
template<typename T>
std::string sin_deg_str(T angle_deg)
{
ostringstream ss;
ss << (sin(angle_deg * (M_PI / 180)));
return ss.str();
}
// ...
if(m_RHS->get_gType() == INT)
return sin_deg_str(m_RHS->evalint());
else
return sin_deg_str(m_RHS->evaldouble());
Not sure you could eliminate the if...then
with a ?:
operator, though, since the types don't match.
Adding more functions? This might work:
template<typename T, typename Function>
std::string call_deg_str(T angle_deg)
{
ostringstream ss;
ss << (Function(angle_deg * (M_PI / 180)));
return ss.str();
}
// ...
if(m_RHS->get_gType() == INT)
return call_deg_str<sin>(m_RHS->evalint());
else
return call_deg_str<sin>(m_RHS->evaldouble());
Upvotes: 2
Reputation: 624
ostringstream ss;
if(m_RHS->get_gType() == INT)
ss << (sin(m_RHS->evalint() * (M_PI / 180)));
else
ss << (sin(m_RHS->evaldouble() * (M_PI / 180)));
return ss.str();
this is the most sipliest
Upvotes: 1