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.
To explicitly answer your question, no that is not possible. The constants can not be represented as datatypes. Show activity on this post. First of all, java doesn't have runtime method overloading.
Detailed Solution. (::) Scope resolution operator cannot be overloaded in C language. Operator overloading:- It is polymorphism in which an operator is overloaded to give user-defined meaning to it. The overloaded operator is used to perform operations on user define data type.
No we cannot overload integer or float types because overloading means to change the working of existing operators or make them to work with objects int is single member not an object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With