为什么结构可以隐式转换以匹配函数的参数类型,但如果它是删除默认值的赋值运算符,则不能?
例子:
struct c{
void operator=(bool){}
operator bool(){
return false;
}
c&operator=(const c&)=delete;
};
void f(bool){}
int main(){
c a,b;
f(b); //works fine
a=b; //g++ -std=c++17 says: error: use of deleted function ‘c& c::operator=(const c&)’
}
为什么f(b)调用转换b为boolmatchf的类型但a=b坚持不转换?
回答
重载解析的工作原理是找到最佳匹配,然后检查函数的可访问性。如果您无法访问该功能,因为它受保护/私有或已删除,那么您会收到错误消息。和
f(b);
唯一有效的选项是operator bool()使代码有效。和
a=b
编译器发现
c&operator=(const c&)
// and the chain
operator bool() -> void operator=(bool)
第一个是更好的匹配,所以它是使用的重载,并且由于它被标记为delete,你会得到一个编译器错误。
THE END
二维码