"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:41***************@gascad.at...
bberu wrote: I know it is possible to refine operators (like +, -, * or /) on classes.
But is it possible on simple types ?
ex :
If I have a type like :
typedef int vector[100]
is it possible to redefine a + operator on the vetor type ?
vector is not a type.
vector is of type: array[100] of int
vector is indeed the name of a type (although a poorly chosen one).
And no. It is not possible to define operators for the built in types.
But the question was not about built-in types.
You can actually overload operators on some simple types such as enum:
enum SimpleType { stA, stB, stC };
SimpleType& operator++(SimpleType& a) {
if(a>=stC) a = stA; else a = static_cast<SimpleType>(a+1);
return a;
}
However, while functions can be overloaded on array parameters,
overloaded operators need to have at least one parameter of
a user-defined type:
typedef int vec3[3];
void add( vec3& a, vec3 const& b ) // ok, fully valid
{
a[0]+=b[0]; a[1]+=b[1]; a[2]+=b[2];
}
void operator++( vec3& a ) // ERROR - op overload requires UDT
{
a[0]+=1; a[1]+=1; a[2]+=1;
}
Anyway, array types have many caveats and limitations
(e.g. implicit conversion to pointers;
cannot be used as function return value).
It is much safer and easier to use a struct wrapping
the fixed-size array:
struct vec100
{
int m[100];
};
All operators can then be overloaded . By adding operator[]
members, you can also support the same syntax as for a
built-in array (and have the possibility to add bounds checks).
Boost and most likely the next version of the standard library
also include a template class that automates this process:
typedef array<int,100> vec100;
Cheers,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form