拥有相同方法的静态和非静态版本是不是设计不好

Is it bad design to have static and non-static versions of the same method

本文关键字:静态 是不是 版本 方法 拥有      更新时间:2023-10-16

我面临的问题与我的记录器库有关。我可以创建自己的记录器,但同时,我希望能够使用"默认"或"全局"记录器进行操作。

所以我认为我的记录器类的一些方法应该有静态版本,这些版本将处理这个"默认"记录器。这最终在设计方面感觉是错误的。

这是我想做的事情的一个例子

std::shared_ptr<lwlog::logger> core_logger = std::make_shared<lwlog::logger>("LOGGER");  //creating some custom logger
core_logger->critical("A very critical message!"); //logging from some custom logger
lwlog::logger::critical("A very critical message!"); //logging from default logger

我的静态和非静态方法版本示例:

class LWLOG logger
{
public:
    explicit logger(const std::string& name);
    ~logger();
    void set_name(const std::string& loggerName);
    void set_logLevel_visibility(log_level logLevel);
    void set_pattern(const std::string& pattern);
    void info(const std::string& message);
    void warning(const std::string& message);
    void error(const std::string& message);
    void critical(const std::string& message);
    void debug(const std::string& message);
    static void info(const std::string& message);
    static void warning(const std::string& message);
    static void error(const std::string& message);
    static void critical(const std::string& message);
    static void debug(const std::string& message);
};

是的,那会非常令人困惑。

类中的成员函数执行任务。任务由函数的名称描述,以及(在某种程度上(它是否static。具有两个名称相同但static不同的成员函数执行两个不同的事情是完全无法使用的。

标准委员会也知道这一点,这就是为什么您提出的解决方案无法编译的原因。

如果您的用户想要使用不同类型的记录器,他们可以随时使用不同的实例执行此操作。

您可以在命名空间中提供一个现成的实例化,以便用户可以执行以下操作:

lwlog::default_logger->critical("Using the default logger for this one");