Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this preprocessor directive acceptable here?

Having a singleton Logger class, I feel like writing Logger::GetInstance() everytime a print method is called is ugly. The only solution I can think of is #define. Is there anything 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");
}
like image 804
Innkeeper Avatar asked Mar 20 '23 08:03

Innkeeper


1 Answers

note, since you're apparently defining a macro "locally", that macros do not respect scopes.

why not just define a function instead of a macro:

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

then you can write just

logger().Print( "Hello" );
like image 187
Cheers and hth. - Alf Avatar answered Apr 01 '23 12:04

Cheers and hth. - Alf