I want to store a sequence of string in a queue. This seems pretty simple if i use the member function push()
queue test;
string s0("s0"), s1("s1");
test.push(s0);
test.push(s1);
I am thinking about adding the strings in the queue in implicitly way. That mean, if I type the following sequence of string the e.g. operator >>
should push the string value in the queue.
queue test;
string s0("s0"), s1("s1");
s0 >> s1 >> s2 >> s3 ;
is there any way to do that?
While C++ doesn't allow you this, it allows you to do something very similar: test << s0 << s1;
However, don't do this!
If I see test.push(s0)
, I know exactly what it does, without even looking at the type of test
. If I see test << s0 << s1;
, I'd think test
is a stream that's written to.
Here's my three basic rules you should stick to when overloading operators:
+
operator to change its right operand. However, the users of such an operator would never suspect the expression a + b
to change the value of b
. This is why the second rule of operator overloading says: Always stick to the operator’s well-known semantics. (This, in turn, presumes that the semantics are undisputed; see the previous rule.) a + b
, users will expect to be able to call a += b
, too. If it supports prefix increment ++a, they will expect a++ to work, too. If they can check whether a < b
, they will most certainly expect to also to be able to check whether a > b
. If they can copy-construct your type, they expect assignment to work as well. So the third rule of operator overloading reminds you: Always provide all out of a set of related operations. As with all such rules, there are indeed exceptions. Sometimes people have deviated from them and the outcome was not bad code, but such deviations are few and far between. At the very least, 99 out of 100 such deviations I have seen were unjustified. However, it might just as well have been 999 out of 1000. So you’d better stick to these rules.
So just in case I hadn't been clear enough: For the code from your question, a deviation from these rules is very bad.
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