Overloading has been a theme in my life for the past year. Those of you who remember my first column for Dr. Dobb's, back in the April issue, have heard it before: Writing a book, moving from Massachusetts to Indiana, buying a house, selling a house, getting married, changing job relationships, going to Standards Committee meetings, editing the draft C++ Standard, writing this column. But I think the worst is nearly over. A month ago I was in Berlin for a C++ Standards Committee meeting; the next one is now a long five months away. Two weeks ago I sold my house. Yesterday I sent the penultimate draft of the book off to the publisher [1]. Later today I leave for Bostonthe wedding is the day after tomorrow. How did I get through it all, you ask. It was easy: I'm lazy.
The fundamental rule of laziness is: Don't do it unless you have to. But that's not a justification for your teenagers refusing to clean up their rooms until you yell at them. There's a more principled meaning to "have to" in that ruleit means setting priorities with an eye toward long-term goals. One of the hardest things to learn, in programming and in life, is that some things are less important than others. Do the things that are most important, and let the things that are less important go. Be lazy.
There was a discussion recently on comp.std.c++ about the best way to write code that loops through the contents of a vector using an index. The natural way to write that loop is:
for (int i = 0; i < vect.size(); ++i) // do whatever you need to do with i
But vect.size() might be a little slow, and if you change to a different kind of container, it might not even be constant time. So some people do this:
const int limit = vect.size(); for (int i = 0; i < limit; ++i) // do whatever you need to do with i
But that makes limit visible to the rest of the code, and someone later on might misuse it. So try this:
{ const int limit = vect.size(); for (int i = 0; i < limit; ++i) // do whatever you need to do with i }
Now limit goes away at the end of the block, and there's no need to worry about excessive scope.
There were several other variants, all dealing with equally unimportant issues. For a vector, size() is trivial. And it's an inline function. Just write the code and get on with the important part, which is making the application work.