[Qt-interest] Semi-OT: indentation with operator<<

Andre Somers andre at familiesomers.nl
Wed Jul 28 20:48:35 CEST 2010


Op 27-7-2010 19:20, K. Frank schreef:
> Hi Atlant -
>
> On Tue, Jul 27, 2010 at 12:06 PM, Atlant Schmidt
> <aschmidt at dekaresearch.com>  wrote:
>    
>> K. Frank:
>>
>>   Yeah, that's basically the idea I had in mind.
>>   One difference between my implementation and
>>   yours:
>>
>>   I conceived of the indent_level starting at -1
>>   so that every "<<" overload could simply increase
>>   the indent level on entry and decrease it on exit,
>>   then doing whatever it wanted to do in-between.
>>      
> Okay, that makes sense.  I had been wondering why you had
> initialized indent_level to -1.
>
>    
>>   That
>>   means that no special action need be taken if one
>>   "<<" overload decides to invoke another"<<" overload
>>   to display the deeper details; all the "<<" overload
>>   operators just "auto-nest" automagically and every
>>   "<<" overload has a very-similar "wrapper" handling
>>   the indent_level: increment on entry, do its thing,
>>   then decrement on exit.
>>
>>   After I wrote my initial reply, I also realized you could
>>   play one more (optional) game with this scheme. Perhaps
>>   you might use a preset indent_level of -2 to indicate
>>   that no debugging output should be generated at all?
>>   Other special values could also be implemented.
>>
>>                         Atlant
>>      
> Thanks for the ideas.
>    
If you want, you could wrap it up into a RAII class, so you can not 
forget about it and early exits and the likes are automatically handled. 
That might make it slightly cleaner to work with, perhaps. The RAII 
class would basically look like this:

class Indenter
{
     public:
     Indenter() {++indentation_level;}
     ~Indenter() {--indentation_level;}
     int level() {return indentation_level;}
}

indentation_level can be a global variable, or a static member variable 
of Indenter. Preferably the latter.
You can then use it in your output by simply creating an instance on the 
stack and reading the level when you need it. Since you created it on 
the stack, the destructor will be called as soon as it goes out of scope.

*That* would IMHO be the C++ way to do it. No hassle with singletons 
needed. At around 10 of these indentation-needing POD's, you have less 
code already, since you loose all those manual decreasements of the 
indentation variable. And you will have less issues with a forgotten 
decreasing somewhere. Sooner or later you, or the one maintaining and 
expanding your code, will.

André




More information about the Qt-interest-old mailing list