Art*_*yom 15 c++ enums operator-overloading
例如,如果我有:
typedef enum { year, month, day } field_type;
inline foo operator *(field_type t,int x)
{
return foo(f,x);
}
inline foo operator -(field_type t)
{
return t*-1;
}
int operator /(distance const &d,field_type v)
{
return d.in(v);
}
Run Code Online (Sandbox Code Playgroud)
因为如果我没有定义这样的运算符,它实际上是合法的day*3
,它会被翻译成6?
它合法吗?
至少gcc和intel编译器在没有警告的情况下接受这个.
Clearification:
我不想要默认算术运算,我想要自己的返回非整数类型的操作.
是的,可以在枚举和类类型上完成运算符重载.你这样做的方式很好,但你应该+
用来推广枚举,而不是*-1
或者某种东西(目的最终是为了避免无限递归,因为-t
):
inline foo operator -(field_type t) {
return -+t;
}
Run Code Online (Sandbox Code Playgroud)
这将很好地适用于其他操作.+
将枚举提升为可以表示其值的整数类型,然后您可以应用-
而不会导致无限递归.
请注意,您operator*
只允许您这样做enum_type * integer
,但不是相反.也许值得考虑另一个方向.
还要注意,内置运算符已经接受的操作数的重载运算符总是有点危险(即使只是通过隐式转换).想象一下,distance
有一个转换构造函数采用int(如在distance(int)
),然后给出你operator/
的以下是不明确的
// ambiguous: operator/(int, int) (built-in) or
// operator/(distance const&, field_type) ?
31 / month;
Run Code Online (Sandbox Code Playgroud)
为此,也许最好field_type
使用适当的运算符创建一个真正的类,以便您可以从begin开始排除任何此类隐式转换.C++ 0x提供了另一个很好的解决方案enum class
,它提供了强大的枚举.