且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不允许使用非成员函数重载C ++转换运算符的原因是什么

更新时间:2023-11-09 19:31:10

使用当前规则,要确定是否可以在两个类之间进行转换,您只需要查看两个位置:源和目标定义。如果您可以将转换定义为非成员函数,则转换函数可能在任何可能导致不必要或模糊转换的原因更困难的地方(除了使编译器更努力地找到可能的转换,需要或可能例如操作员重载)。

With the current rules, to work out whether you can convert between two classes you only need to look in two places: the source and target definitions. If you could define conversions as non-member functions the conversion function could be anywhere which might make finding the cause of unwanted or ambiguous conversions much more difficult (in addition to making the compiler work harder to find possible conversion in all cases where a conversion was need or possible e.g. operator overloading).

我不认为你提出的模板将是非常实用的。虽然您可以明确专门针对转换进行转换,但您有适当的特殊情况,但仍会捕获所有其他转换,从而导致任何预先存在的转换造成歧义。

I don't think that your proposed template would be very practical. Although you could explicitly specialize it for conversion where you did have an appropriate special case, it would still catch all other conversions causing ambiguities with any pre-existing conversions.

或许不允许这种转换的两个潜在因素。

These are perhaps two potential factors in not allowing such conversion.