模板赋值运算符重载之谜 [英] Template assignment operator overloading mystery
问题描述
我有一个简单的结构 Wrapper
,以两个模板化的赋值运算符重载来区分:
I have a simple struct Wrapper
, distinguished by two templated assignment operator overloads:
template<typename T>
struct Wrapper {
Wrapper() {}
template <typename U>
Wrapper &operator=(const Wrapper<U> &rhs) {
cout << "1" << endl;
return *this;
}
template <typename U>
Wrapper &operator=(Wrapper<U> &rhs) {
cout << "2" << endl;
return *this;
}
};
然后我声明 a 和 b:
I then declare a and b:
Wrapper<float> a, b;
a = b;
将 b
赋值给 a
将使用上面的非常量模板赋值运算符重载,并显示数字2".
assigning b
to a
will use the non-const templated assignment operator overload from above, and the number "2" is displayed.
令我困惑的是:如果我声明 c
和 d
,
What puzzles me is this: If I declare c
and d
,
Wrapper<float> c;
const Wrapper<float> d;
c = d;
并将d
赋值给c
,两个赋值运算符重载都没有使用,不显示输出;所以调用了默认的复制赋值运算符.为什么将 d
分配给 c
不使用提供的 const 重载赋值运算符?或者相反,为什么将 b
分配给 a
不 使用默认的复制赋值运算符?
and assign d
to c
, neither of the two assignment operator overloads is used, and no output is displayed; so the default copy assignment operator is invoked. Why does assigning d
to c
not use the const overloaded assignment operator provided? Or instead, why does assigning b
to a
not use the default copy assignment operator?
推荐答案
为什么将
d
赋值给c
不使用提供的 const 重载赋值运算符?
Why does assigning
d
toc
not use the const overloaded assignment operator provided?
隐式声明的复制赋值运算符,声明如下,仍然生成:
The implicitly-declared copy assignment operator, which is declared as follows, is still generated:
Wrapper& operator=(const Wrapper&);
运算符模板不会抑制隐式声明的复制赋值运算符的生成.由于参数(const 限定的 Wrapper
)与此运算符的参数(const Wrapper&
)完全匹配,因此在重载解析期间选择它.
An operator template does not suppress generation of the implicitly-declared copy assignment operator. Since the argument (a const-qualified Wrapper
) is an exact match for the parameter of this operator (const Wrapper&
), it is selected during overload resolution.
未选择操作符模板并且没有歧义,因为——所有其他条件都相同——在重载解析期间,非模板比模板更匹配.
The operator template is not selected and there is no ambiguity because--all other things being equal--a nontemplate is a better match during overload resolution than a template.
为什么将 b
赋值给 a
不使用默认的复制赋值运算符?
Why does assigning
b
toa
not use the default copy assignment operator?
参数(非const限定的Wrapper
)与采用Wrapper<U>&
的操作符模板相比,比隐式-声明的复制赋值运算符(它需要一个 const Wrapper&
.
The argument (a non-const-qualified Wrapper
) is a better match for the operator template that takes a Wrapper<U>&
than for the implicitly-declared copy assignment operator (which takes a const Wrapper<U>&
.
这篇关于模板赋值运算符重载之谜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!