Is it always safe to use C ++ 14 to automatically return a function type instead of std :: common_type?

I am updating part of my codebase from C ++ 11 to C ++ 14. I have several mathematical utility functions that take several input arguments and return a single value of type std::common_type_t<...> .

I am thinking of replacing an explicit return value with a simple auto . I think the type deduction is really trying to find a common type in these cases. Are there any cases where this will not work?

Is it safe to convert all occurrences of returned std::common_type_t<...> values ​​with auto ?

Function example:

 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); } 
+6
source share
1 answer

No, this is not always safe.

I suppose your math functions do more than that, 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 , the result will be char . You would automatically infer the return type, this would give an int .

+7
source

Source: https://habr.com/ru/post/975366/


All Articles