Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always safe to use C++14's auto function type return deduction in place of std::common_type?

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);
}
like image 252
Vittorio Romeo Avatar asked Sep 16 '14 17:09

Vittorio Romeo


1 Answers

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 chars the result will be a char. Would you auto deduce the return type, it would yield an int.

like image 139
D Drmmr Avatar answered Oct 22 '22 20:10

D Drmmr