我可以使用C ++中的枚举类型重载操作符吗? [英] Can I overload operators on enum types in C++?
问题描述
例如,如果我有:
typedef枚举{年,月,日} 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);
}
因为如果我没有定义这样的运算符,写入 day * 3
而
将被翻译成6?
那么是合法的吗?
至少gcc和intel编译器接受这个没有警告。
清除:
我不想要默认算术运算,我想要我自己的操作返回非整数类型。
+
来提升枚举,而不是 * - 1
或一些东西(最终的目的是避免无限递归,因为 -t
): inline foo operator - (field_type t){
return - + t;
}
这将适用于其他操作。 +
会将枚举提升为可表示其值的整数类型,然后可以应用 -
而不会导致无限大递归。
请注意,您的运算符*
只允许您 enum_type * integer
,但不是相反。可能值得考虑的另一个方向。还要注意,内置运算符已经接受的操作数(即使只是通过隐式转换),重载操作符总是有点危险。想象一下,距离
有一个转换构造函数,取int(如 distance(int)
),然后给出你的 operator /
以下是不明确的
// ambiguous:operator /(int,int )(内置)或
//操作符/(distance const& field_type)?
31 /月;
为此,也许最好让 field_type
一个具有适当运算符的真实类,以便您可以从开始排除任何这样的隐式转换。另一个好的解决方案是由C ++ 0x的枚举类
提供,它提供强大的枚举。
For example, if I have:
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);
}
Because if I do not define such operators it is actually legal to write day*3
and it
would be translated into 6?
So is it legal?
At least gcc and intel compiler accept this without a warning.
Clearification:
I do not want default arithmetic operations, I want my own operations that return non-integer type.
Yes, operator overloading can be done on enum and class types. The way you do it is fine, but you should use +
to promote the enumeration, instead of *-1
or something (the purpose ultimately is to avoid infinite recursion because -t
):
inline foo operator -(field_type t) {
return -+t;
}
This will scale well to other operations. +
will promote the enumeration to an integer type that can represent its value, and then you can apply -
without causing infinite recursion.
Notice that your operator*
does only allow you to do enum_type * integer
, but not the other way around. It may be worth considering the other direction too.
Also notice that it's always a bit dangerous to overload operators for operands that builtin-operators already accept (even if only by implicit conversions). Imagine that distance
has a converting constructor taking int (as in distance(int)
), then given your operator/
the following is ambiguous
// ambiguous: operator/(int, int) (built-in) or
// operator/(distance const&, field_type) ?
31 / month;
For this, maybe it's better to make field_type
a real class with the appropriate operators, so that you can exclude any of such implicit conversions from begin on. Another good solution is provided by C++0x's enum class
, which provides strong enumerations.
这篇关于我可以使用C ++中的枚举类型重载操作符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!