2016-10-05 58 views
2

我有这个程序有2模板功能:模板调用似乎UNMATCH

#include <iostream> 
template <class T> void assign(T& t1,T& t2){ 
    std::cout << "First method"; 
    t1=t2; 
} 
template <class T> void assign(T& t1,const T& t2) { 
    std::cout << "Second method"; 
    t1=t2; 
} 
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) { 
    return A(l._a+r._a); 
} 
int main() 
{ 
    A a=1; 
    const A b=2; 
    assign(a,a+b); 
} 

我无法理解为什么用assign(a,a+b)调用中的第二模板函数 ,在operator+我们createing新A对象,用int参数调用ctor。

它创建a+b作为const对象?

+4

非const左值裁判不绑定到临时对象。 –

回答

1

它创建一个+ b作为const对象?

不,它正在创建一个临时的。临时被绑定到右值引用。您可以验证与“第三”功能(通用参考,在这种情况下)

template <class T> 
void assign(T& t1, T&& t2) { 
    std::cout << "Third method"; 
    t1=t2; 
} 

当你没有一个,编译器将选择常量引用过载。为什么?

假设你有

void add(int & x) 
{ 
    ++x; 
} 
unsigned y = 0; 
add(y); // create a temporary to int 
std::cout << y << "\n"; // what's the value of y ? 
相关问题