拥有相同方法的静态和非静态版本是不是设计不好
Is it bad design to have static and non-static versions of the same method
我面临的问题与我的记录器库有关。我可以创建自己的记录器,但同时,我希望能够使用"默认"或"全局"记录器进行操作。
所以我认为我的记录器类的一些方法应该有静态版本,这些版本将处理这个"默认"记录器。这最终在设计方面感觉是错误的。
这是我想做的事情的一个例子
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");
相关文章:
- 在调用接收数组的方法时,模板化数组大小是不是一种糟糕的做法
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 在枚举类型上使用std::max是不是一种糟糕的做法
- 在这种情况下,我们可以使用静态而不是朋友吗,还有其他解决方案是什么
- std::元组大小,是不是错过了优化?
- 拥有相同方法的静态和非静态版本是不是设计不好
- 他是不是很贪婪
- SDL2:移动所有东西而不是使用视图端口是不是很糟糕
- OOP-我是不是把事情复杂化了
- 在DLL中分配内存并将其指针提供给客户端应用程序,这是不是一种糟糕的做法
- 在C++代码中使用C风格的注释是不是一种糟糕的做法
- 如果我在C++中使用堆,我是不是做错了什么
- 这个简单但有用的模式是不是太简单了,不可能成为一个真正的模式
- 在C++中,通过引用传递常量布尔值是不是不好的
- 在main.cpp中而不是在头文件中定义函数是不是一种糟糕的做法
- 既然智能指针已经存在,那么使用C型指针是不是已经过时了
- LNK2019:未解析的外部符号;我是不是忘了
- 奇怪的无符号静态常量不是类模板中的常量表达式
- 在类中不定义静态数组大小是不是很糟糕--而是让它自动缩放
- C++:为了便于访问,在类中使用静态容器来包含指向其所有对象的指针是不是一种糟糕的做法