I am trying to overload operator <<
, but it always need to be a const
function. However, I want to change values inside this overloaded function
The reason you're having trouble here is that this is an inappropriate use of operator overloading. Operator overloading is best used in these spots:
operator =
.operator <<
for stream insertion or operator <
to store your type in the standard container classes.operator ()
.The code you have above does not fall into any of these categories, and consequently any use of it is likely to confuse people. For example, if someone not well-versed with your project sees something like this:
myCheck << myValue;
They are likely to be thinking "oh, that's some sort of stream insertion" or "oh, that's a mathematical type getting bit-shifted over." However, in your case this code really means "have the checker object myCheck
validate myValue
." If that's what you want to do, then write something more explicit like
myCheck.validate(myValue);
Now, someone looking over your code can get a much better sense for how it works and what it's trying to do.
In general, think about the Principle of Least Astonishment when writing code - code shouldn't surprise you about how it works. By using operator <<
in a nonstandard context, you are likely to cause programmers to misinterpret your code or have a hard time understanding what it does. Being more explicit about your intentions by using named functions rather than overloaded operators in this and related contexts makes the code more readable and decreases the chance that the code will trip up people reading it.
Now, as for an actual answer to your question. There is no requirement that operator <<
be a const
member function. Think about the standard streams classes like cout
or ofstream
; the operation
cout << "Hello, world!" << endl;
Certainly modifies cout
by pushing new data into it, just as the operation
cout << setfill('0') << left << hex;
Modifies cout
by changing the formatting flags. So, if you want your operator <<
function to mutate the object the data is pushed into, by all means go ahead and make it a non-const
member function. C++ doesn't have any expectations about the const
ness or non-const
ness of any overloaded operators, so you should be perfectly fine.