By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,968 Members | 1,852 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,968 IT Pros & Developers. It's quick & easy.

operator overloading

P: 38
Hi all,

I want to implement an operator to be able to store strings in a queue implicitly through an operator. Something like that:

Expand|Select|Wrap|Line Numbers
  1. ...
  2.  
  3. SetString( )
  4.  
  5. {
  6. string1 >> string2 >> string3 >> string4 >> string5
  7.  
  8.  

The operator ">>" should then read each string and store it in a global queue by calling the queue's member function "push()".

Is there any way to implement such operator.

regards
Sep 2 '10 #1
Share this Question
Share on Google+
2 Replies


Banfa
Expert Mod 5K+
P: 8,916
Probably but don't.

That is not the proper semantic meaning of the >> (right shift) operator. I know the stand C++ libraries own stream classes use this operator in this way but IMO there is no good reason to propagate that piece of cannibalisation of an operator.

Just call the queues push function repeatedly. This will also have the effect of making it very clear to anyone reading your code what is happening.

And talking of the queue... don't use global data.


This is one of those cases of the C++ language telling you do things that are all very clever but that in the long run provide little or no advantage but do make you software less maintainable through obfuscation.
Sep 2 '10 #2

Oralloy
Expert 100+
P: 983
mar11,

I hate to say it, but Banfa has the right of it.

The smart implementation is to build a method that chains:
Expand|Select|Wrap|Line Numbers
  1. inline myQue &append(string const &value)
  2. {
  3.   this.push(value);
  4.   return this;
  5. }
  6.  
Since this chains, you can easily write:
Expand|Select|Wrap|Line Numbers
  1. myQueObject.append(string1).append(string2).append(string3);
  2.  
Of course, if you really want to operator overload, you can:
Expand|Select|Wrap|Line Numbers
  1. inline string &operator >>(string const &value0, string const &value1)
  2. {
  3.   ...
  4. }
  5.  
But beware the maintenence programmer who follows in your footsteps and has to work with your code. The construct you proposed is completely non-obvious. If it's to save a few keystrokes, just say no. Code should be clear, not cryptic.

Also, just as an observation, how do you push a single value? It looks like your construct takes a minimum of two strings.
Sep 2 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.