我想将用户定义的运算符用于类内部的类型:
class TWithUserDefinedOp
{
private: int a{42};
public: operator *(const TWithUserDefinedOp& other) { return a * other.a;}
};
class Wrap
{
private: TWithUserDefinedOp a;
public: operator TWithUserDefinedOp() const { return a; }
}
现在,当我想要多个Wrap
类时,我希望它能正常工作
Wrap a, b;
auto mul = a * b; //Error: Wrap does not define this operator or a conversion to a type acceptable to the predefined operator
现在,如果我更改换行以容纳整数类型:
class WrapIntegral
{
private: int a{42};
public: operator int() const { return a; }
}
现在可以进行乘法。
WrapIntergal a,b;
auto mulInt = a * b; // this works ok
[我在其他类似问题中读到,C++
仅允许1级隐式转换。如果我计算正确,第一个示例中只有一个隐式转换。从Wrap
到定义了TWithUserDefinedOp
的operator *
。我的误解是什么?我在这里做什么错?
此
auto mul = a * b;
与]相同>
auto mul = a.operator(b);
隐式转换应用于参数,而不是运算符的左侧。否则,编译器将必须检查定义了
*
运算符的每个类型是否具有可行的转换,最终将导致歧义(因为不太可能只有一个匹配项)。