operator overloading

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mar11
    New Member
    • Sep 2009
    • 38

    #1

    operator overloading

    Hi all,

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

    Code:
    ...
    
    SetString( )
    
    {
    string1 >> string2 >> string3 >> string4 >> string5
    
    }

    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
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    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.

    Comment

    • Oralloy
      Recognized Expert Contributor
      • Jun 2010
      • 988

      #3
      mar11,

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

      The smart implementation is to build a method that chains:
      Code:
      inline myQue &append(string const &value)
      {
        this.push(value);
        return this;
      }
      Since this chains, you can easily write:
      Code:
      myQueObject.append(string1).append(string2).append(string3);
      Of course, if you really want to operator overload, you can:
      Code:
      inline string &operator >>(string const &value0, string const &value1)
      {
        ...
      }
      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.

      Comment

      Working...