简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM