I don’t understand why the output of this program is Second method instead of First Method…
#include <iostream>
template <class T>
void assign(T& t1,T& t2){
std::cout << "First method"<< std::endl;
}
template <class T>
void assign(T& t1,const T& t2) {
std::cout << "Second method"<< std::endl;
}
class A
{
public:
A(int a):_a(a){};
private:
int _a;
friend A operator+(const A& l, const A& r);
};
A operator+(const A& l, const A& r) {
friend A operator+(const A& l, const A& r);return A(l._a+r._a);
}
int main ()
{
A a=1;
const A b=2;
assign(a,a+b);
}
However, when I change my main function to this:
int main ()
{
A a=1;
const A b=2;
A c=a+b;
assign(a,c);
}
The output is First method.
Any ideas?
The result of
a + bis an rvalue expression of typeAthat creates a temporary and you cannot bind it to a non-const reference, so it picks up theconstoverload as you are allowed to bind a const reference to a temporary.In this case, the subexpression
cis an lvalue expression and you are allowed to bind a non-const reference. In this case, because the non-const version is a perfect match withT=Ait is preferred over the const overload that would require a conversion in the second argument from an lvalue of typeAto const lvalue of typeA.