473,804 Members | 3,043 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Redefining operators in C++

Hi,

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 ?

Thanks !
Bruno
Jul 22 '05 #1
7 4568
bberu wrote:

Hi,

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

And no. It is not possible to define operators for the built in types.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #2
"Karl Heinz Buchegger" <kb******@gasca d.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++(Simp leType& a) {
if(a>=stC) a = stA; else a = static_cast<Sim pleType>(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
Jul 22 '05 #3
Ivan Vecerina wrote:
"Karl Heinz Buchegger" <kb******@gasca d.at> wrote in message
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 };
To overload an operator, one operand must be of class or enum type.
Enum is NOT a simple type.

However, while functions can be overloaded on array parameters,
Nope. Any array in a function argument is converted to pointer to
the element type for the purposes of overloading.
void add( vec3& a, vec3 const& b ) // ok, fully valid
and identical to:
void add(int*&, int*const& )
for overloading purposes. This is an important distinction as:
typedef int vec4[4];
void add(vec4, vec4);
void add(vec3, vec3);
yield the same signature and make the program ill-formed.

It is much safer and easier to use a struct wrapping


Jul 22 '05 #4
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 ?


Hi!

vector is NOT a type. vector is a type-alias for "int [100]"
So no, you can't overload operators, since at least one argument of on
overloaded operator needs to be of class-type (user defined type).
You might do something like:
struct my_vector
// don't just use "vector" because everybode who reads it will
// immediately think so std::vector<> which is a completely different
// thing
{
int elements[100];
};

Then you can overload any operator + or whatever you like.
If you want you can overload operator [] to enable direct access to the
elements. You might even check the index inside that operator, which is
a nice thing to have, at least for debug builds.
Bye,
'monster
Jul 22 '05 #5
"Ron Natalie" <ro*@sensor.com > wrote in message
news:41******** *************** @news.newshosti ng.com...
Ivan Vecerina wrote:
"Karl Heinz Buchegger" <kb******@gasca d.at> wrote in message 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 };
To overload an operator, one operand must be of class or enum type.
Enum is NOT a simple type.


Does your claim have any basis in the C++ standard?
From a naive perspective, an enum is pretty much a simple type.
From a formal perspective, SimpleType would qualify as
a "Simple type specifier"(§7.1 .5).
But the real point is that I don't think that the unspecific
wording should be interepreted to the detriment of the OP.
However, while functions can be overloaded on array parameters,


Nope. Any array in a function argument is converted to pointer to
the element type for the purposes of overloading.


Not if this array is passed by reference, as in the example
I provided.
See §8.3.5: the decay of array to pointer applies if the
parameter is of type "array of T". This does not include
parameters that would be of type "reference to array of T".
void add( vec3& a, vec3 const& b ) // ok, fully valid


and identical to:
void add(int*&, int*const& )
for overloading purposes.


Not true - a reference to a pointer is not equivalent to
a reference to an array.
Did you try to compile the sample code I had provided ?

This is an important distinction as:
typedef int vec4[4];
void add(vec4, vec4);
void add(vec3, vec3);
yield the same signature and make the program ill-formed.


Yes - in your modified example.
But the following functions have distinct signatures:
void add(vec4&, vec4&);
void add(vec3&, vec3&);

It is much safer and easier to use a struct wrapping

And we naturally agree on that, I believe.
Regards,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Jul 22 '05 #6
Ivan Vecerina wrote:
To overload an operator, one operand must be of class or enum type.
Enum is NOT a simple type.

Does your claim have any basis in the C++ standard?
From a naive perspective, an enum is pretty much a simple type.


Certainly, or I would not have made it. 3.9.2 defines enum
as a compound type.
From a formal perspective, SimpleType would qualify as
a "Simple type specifier"(§7.1 .5).
A simple type specifier is just one that can be expressed as
a single word. It can be anything from a class to a int.
There are fundamental types (the proper antonym to compound
type) that are not expressed with simple type specifiers:
unsigned short
is not.
std::exception
is.

Jul 22 '05 #7
"Ron Natalie" <ro*@sensor.com > wrote in message
news:41******** *************** @news.newshosti ng.com...
Ivan Vecerina wrote:
To overload an operator, one operand must be of class or enum type.
Enum is NOT a simple type.

Does your claim have any basis in the C++ standard?
From a naive perspective, an enum is pretty much a simple type.


Certainly, or I would not have made it. 3.9.2 defines enum
as a compound type.


So let's call it a simple compound type ;)
I just disagree that "simple" had to imply "fundamenta l"
in the context of the OP.

Kind regards,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Jul 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
2534
by: greg | last post by:
Discussion is invited on the following proto-PEP. ------------------------------------------------------------- PEP ??? - Overloadable Boolean Operators ======================================== SUMMARY This PEP proposes an extension to permit objects to define their own
1
2373
by: Xiangliang Meng | last post by:
Hi, all. When reading C++ books, I'm alway confused by those terms "redefining functions", "overloading functions" and "overriding functions". Please give me some comments on those terms. Thanks. If giving more strategy hehind them, more helpful. Best Regards,
1
860
by: bberu | last post by:
> Ivan Vecerina and Swampmonster wrote: > > 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 > >> is it possible to redefine a + operator on the vetor type ?
3
1953
by: notme | last post by:
I have code with lots of "new int..." etc.. I'd like to replace every instance with "new(allocInfo) int" (that is, using placement new) I tried doing: #define new (new(allocInfo)) but that doesn't work... any hints? Thanks!
2
3469
by: Steve Summit | last post by:
-----BEGIN PGP SIGNED MESSAGE----- It's often explained that the reason for some of the imprecision in C's definition is so that C can be implemented on different kinds of machines -- say, those with 2's complement, 1's complement, or sign-magnitude arithmetic. But the followup remark is sometimes also made that the choice of arithmetic isn't completely unconstrained, since the bitwise operators seem to presume a base-2 machine.
49
14915
by: raju | last post by:
hi can we compare two integers without using relational operators (== != < <= > >=) thanks rajesh s
17
2448
by: Steve R. Hastings | last post by:
I have been studying Python recently, and I read a comment on one web page that said something like "the people using Python for heavy math really wish they could define their own operators". The specific example was to define an "outer product" operator for matrices. (There was even a PEP, number 211, about this.) I gave it some thought, and Googled for previous discussions about this, and came up with this suggestion: User-defined...
4
3896
by: allan.mcrae | last post by:
As part of a very simple memory leak detector, I am trying to store the value of __FILE__ in a char*. Since gcc4.2 I get the following warning... warning: deprecated conversion from string constant to 'char*' object. The macro of delete assigns this to a global char* which is used to track where deletions were made. Something like: #define delete delete_FILE_ = __FILE__, \
4
1876
by: Belebele | last post by:
The following code fails to compile. My intention is to provide different definitions for a nested class for a class template partial specialization. Here it is: template <typename , int class Outer { public: class Inner; };
0
9579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10571
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9143
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7615
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6851
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5520
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4295
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.