Re: Variables in for loop (style issue)
Walter Bright wrote:
Thorsten Ottosen wrote:
Walter Bright wrote:
Thorsten Ottosen wrote:
Walter Bright wrote:
P.S. I've never understood why one would want to overload const and
non-const functions with otherwise the same argument types. (Setting
aside template type traits tricks for the moment.)
I think std::vector<T> is a good example. Take the iterator interface:
template< ... >
class vector
{
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
};
because begin() and end() are overloaded on const, vector<T>
will propagate constness for me.
Ok, I understand - both functions have the exact same implementation,
the only reason for the duplication is to propagate const from the
parameter to the return type.
Yes.
It's a problem that one has to make a clone of the function in order to
work around what is essentially a defect of the typing system:
As the programmer, I've got to copy/paste code, then carefully insert
the const's in the right place.
As a code reviewer, I've got to check that the two functions have
identical implementations - except where the const differs - not a thing
the human brain is very good at.
As a maintainer, I've got to be sure and propagate bug fixes in one
function to the other. Better not forget!
As a QA guy, I've got to write double the number of test cases to make
sure both functions are fully tested.
As the bloat cop, I've got two functions doing the same thing, taking up
space.
As the tech writer, I have two functions that need documentation.
As the user, I've got two functions to learn instead of one, and hope
they actually do do the same thing.
If the function is not trivial, one can usually forward to a single
private function.
In order to be const-correct, how often does this happen? (I count 8
times for std::vector, is that representative?)
It happens more often for library code than for user's code. It's quite
common that a user-declared interface has only const versions of inspectors.
There's got to be a better way.
It would be nice to some sort of language support to help to make the
implementation easier.
But otherwise, I wouldn't count a better way.
-Thorsten
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]