该预处理器指令在这里可以接受

Is this preprocessor directive acceptable here?

本文关键字:在这里 预处理 处理器 指令      更新时间:2023-10-16

拥有单顿Logger类,我觉得每次都称为"打印方法"时写Logger::GetInstance()很丑陋。我唯一能想到的解决方案是#define。有什么更好的,还是在这种情况下这宏是合理的?

#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");
}

注意,由于您显然是在局部定义宏,所以宏不尊重scopes

为什么不只是定义函数而不是宏:

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

然后您可以写

logger().Print( "Hello" );

Cheers和Hth的两种替代方案。 - ALF的答案:

,如果您在范围内需要多次需要一次名称:

Logger& logger = Logger::GetInstance();
// ...
logger.Print("Hello, world");

,也可以使记录方法也静态:

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

,然后静态地称呼它们:

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

您可能会争辩说,对于客户端,是否实际上有实例无关紧要 - 构造函数是私人的,因此他们无论如何都无法创建自己的实例。因此,静态方法是否创建实例不应该关注它们。在这种情况下,拥有称为GetInstance的公共方法实际上会暴露出无关的实现细节。