I'm upgrading part of my codebase from C++11 to C++14. I have several math utility functions that take multiple input arguments and return a single value of type std::common_type_t<...>
.
I'm thinking of replacing the explicit return value with a simple auto
. I think that type deduction does try to find a common type in these cases. Is there any case where this wouldn't work?
Is it always safe to convert all occurrences of std::common_type_T<...>
return values with auto
?
Example function:
template<typename T1, typename T2, typename T3>
std::common_type_t<T1, T2, T3> getClamped(T1 mValue, T2 mMin, T3 mMax)
{
return mValue < mMin ? mMin : (mValue > mMax ? mMax : mValue);
}
No, it's not always safe.
I assume your math functions do more than this, but here is an example where the result will be different.
template <class T, class U>
std::common_type_t<T, U> add(T t, U u) { return t + u; }
If you call this function with two char
s the result will be a char
. Would you auto deduce the return type, it would yield an int
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With