I am trying to understand better when decay or not a type
#include <type_traits>
template <typename T1, typename T2> auto max_test(T1 a, T2 b) -> typename std::decay<decltype(a < b ? a: b)>::type {
return a > b ? a : b;
}
template <typename T1, typename T2> auto max_test_r(T1 a, T2 b) -> decltype(a < b ? a: b) {
return a > b ? a : b;
}
Which is the most correct version and why? Should i avoid using decays or when should i use them?
CodePudding user response:
Which is the most correct version and why?
The correct one is the second one, without the std::decay
as you want to return the same type of either a
or b
. That means either T1
or T2
.
Should I avoid using
std::decay
s or when should I use them?
This has been better explained in this post: What is std::decay and when it should be used?
That being said, in C 17 you only need something without the trailing return.
template <typename T1, typename T2>
auto max_test_r(T1 a, T2 b)
{
return a > b ? a : b;
}
You use std::decay
if you want the actual type without the const- volatile qualifiers.
CodePudding user response:
Which is the most correct version and why?
The purpose of std::decay
is to remove the reference and cv-qualifier of the type, but since your function is pass by value, T1
and T2
are already "decayed" types, that is, they are not reference types and do not have cv-qualifier, so it is meaningless to use std::decay
.