模板分配运算符重载奥秘 [英] 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:
Wrapper<float> a, b;
a = b;
指派 b
至 a
assigning b
to a
will use the non-const templated assignment operator overload from above, and the number "2" is displayed.
对我有用[0]丢个板砖[0]如果我声明 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.
没有选择运算符模板,并且没有歧义,因为 - 所有其他事情都相等 - 在重载解析期间,非模板是比模板更好的匹配。 / p>
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>& a
const Wrapper< U>&
。
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屋!