I want to build a printer class that co-manages the indentation level automatically by an Indentation level destructor.
However, this code uses a static indentation level, it works well for a single instance. What workaround I can make to make a unique indentation level across several instances?
#include <stdio.h>
#include <string>
class Logger
{
std::string _tag;
protected:
public:
class Indents
{
public:
Indents () { indents ; };
~Indents () { indents--; };
};
static int indents;
Logger (const std::string & tag):_tag (tag)
{
}
void I (const std::string & info)
{
for (int i = 0; i < indents; i )
printf ("\t");
printf ("%s:\t", _tag.c_str());
printf ("%s\n", info.c_str());
}
};
int Logger::indents = 0;
Logger x ("Service X");
int main ()
{
{
auto a = Logger::Indents();
x.I ("Hello");
}
x.I ("World");
return 0;
}
Prints:
Service X: Hello
Service X: World
CodePudding user response:
you capture the Logger
instance to Indents
.
(and change Logger::indents
to non-static)
class Logger{
int indents = 0; // no more static
public:
struct Indents{
Indents (Logger& logger):logger(logger) { logger.indents ; };
~Indents () { logger.indents--; };
Logger& logger;
};
};
then you can either directly use it
void foo(){
Logger x;
Logger::Indents indent{x};
}
or write a member function to return it
class Logger{
// ...
Indents indent(){return {*this};}
};
// use
void foo(){
Logger x;
auto indent = x.indent();
}