Is this preprocessor directive acceptable here?

Having a singleton class Logger, I like to write Logger::GetInstance()every time the print method is called, is ugly. The only solution I can think of is this #define. Is there something better, or is this macro justified in this situation?

#include <iostream>
#include <fstream>

class Logger
{
public:

    static Logger& GetInstance();
    ~Logger();
    template <typename T>
    void   Print(const T &t);
    void   SetNewline(bool b);
    void   SetLogging(bool b);

private:

    Logger();
    Logger(const Logger&);
    void operator=(const Logger&);

    bool newline;
    bool log;
    std::ofstream file;
};

int main()
{
    #define logger Logger::GetInstance()
    logger.Print("Hello");
    //Logger::GetInstance().Print("Hello");
}
+4
source share
2 answers

Two alternatives to Cheers and hth. - Alf's answer:

You can give the registrar a name if you need it more than once in the field:

Logger& logger = Logger::GetInstance();

// ...

logger.Print("Hello, world");

Or you can also set logging methods:

static void Logger::Print(const T &t) {
   Logger::GetInstance().Print(t);
}

and then name them statically:

Logger::Print("Hello world!");

, , - , . , , , . , GetInstance, .

+3

, , -, "", .

:

inline
auto logger() -> Logger& { return Logger::GetInstance(); }

logger().Print( "Hello" );
+4

Source: https://habr.com/ru/post/1530453/


All Articles