我有这个程序有 2 个模板函数:
#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+
中,我们正在创建一个新的 A
对象并使用 int 参数调用 ctor。
它正在创建 a+b
作为 const 对象?
最佳答案
it is creating a+b as const object ?
不,它正在创建一个临时的。临时对象绑定(bind)到右值引用。您可以使用“第三个”功能(在本例中为通用引用)进行验证
template <class T>
void assign(T& t1, T&& t2) {
std::cout << "Third method";
t1=t2;
}
由于您没有,编译器将选择 const 引用重载。为什么?
假设你有
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 ?
关于c++ - 模板调用似乎不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39882321/