template <typename T>
T operator+(T a, const T& b) {
a += b;
return a;
}
template <typename T>
T operator+(const T& a, const T& b) {
T tmp {a};
tmp += b;
return tmp;
}
Is there any reason why you would pass argument as constant reference like the second function, over directly passing by value like the first function, since you need a temporary variable anyway?
Edit 1:
I think I should mention that these 2 functions alternative are just for handling case with lvalue arguments, and that I am to provide 2 other functions for handling with rvalue arguments, as follows.
template <typename T>
T operator+(T&& a, const T& b) {
a += b;
return std::move(a);
}
template <typename T>
T operator+(const T& a, T&& b) {
b += a;
return std::move(b);
}
So the emphasis of the question is, why would I need to explicitly create a temporary variable (function 2), when I can just let the language facilitate that automatically for me (function 1)?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…