Say I have something like the following, or very similar to it:
Code:
template <typename T1, typename T2>
auto function(T1 &&t1, T2 &&t2) -> typename std::common_type<T1, T2>::type &&
{
if (t1 > t2) return std::forward<T1>(t1);
return std::forward<T2>(t2);
}
The issue I'm having here is that I'm not so sure this is correct for what I want to do. I'd like to end up with a solution that would allow me to modify the variable on the caller's side from the function return (lvalue reference).
Ex:
Code:
function(...) = new_value;
The code above works (somewhat), but seems bugged. I am certain it has to do with the fact that the common type found might not match T2's type if T1 was found to be the common type, or the reverse. So when I try to do anything with the return, type conflict happens.
I can see this being an issue if I wanted to have the function being called, act as an lvalue reference and the common type is T1, so the return would be the value of t2, in T1's type, as some kind of reference, which I doubt will work...
An example of that:
Code:
template <typename T1, typename T2>
auto function(T1 &&t1, T2 &&t2) -> typename std::common_type<T1, T2>::type &&
{
if (t1 > t2) return std::forward<T1>(t1);
return std::forward<T2>(t2);
}
Code like this seems to work:
Code:
int val1 = 1;
long val2 = 2;
auto &&q = function(std::move(val1), std::move(val2));
++q;
std::cout << val1 << std::endl;
std::cout << val2 << std::endl;
And modifies val2 to be 3... But if val1 is higher than val2, val1 never gets modified to be 2, and most likely because the common type is long, but trying to modify that value from a reference to type long isn't going to work...?
I also get a warning about returning a reference to a temp variable, which is confusing because it seems to work as though it's modifying the value from the caller of the function, and not some temp in the function that I wouldn't see change.
Can anybody help clear the confusion here? :S
For a function with 1 template type, it seems simple enough:
Code:
template <typename T>
T && f(T &&x, T &&y)
{
return x > y ? std::forward<T>(x) : std::forward<T>(y);
}