[英]how to avoid using ifdef to make code more testable
I am creating a log file for logging information. 我正在创建用于记录信息的日志文件。 It has a switch to turn it on or off. 它有一个开关可以打开或关闭它。
#define LOG_FILE
#ifdef LOG_FILE
#define LOG(MESSAGE1, MESSAGE2) log(MESSAGE1, MESSAGE2);
#else
#define LOG(MESSAGE1, MESSAGE2)
#endif
Now I can control logging using LOG_FILE switch. 现在,我可以使用LOG_FILE开关控制日志记录。 I was wondering there are any other way achieve similar feature which is more testable? 我想知道是否还有其他方法可以实现类似的功能,而这种功能更易于测试?
You can use templates like this: 您可以使用如下模板:
#include <string>
#include <iostream>
#define USE_LOGGING true
template<bool>
inline void log(const std::string& message, const std::string& verbosity) {}
template<>
inline void log<true>(const std::string& message, const std::string& verbosity) {
std::cout << verbosity << ": " << message << "\n";
}
constexpr auto logMessage = log<USE_LOGGING>;
int main(int argc, char** argv) {
logMessage("Test", "Warning");
}
By this you will have both versions available, using logMessage gives you the global settings, alternatively you can use log directly which is a local definition of how to use logging. 这样,您将拥有两个版本,使用logMessage可以为您提供全局设置,或者您可以直接使用log,它是如何使用日志的本地定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.