该预处理器指令在这里可以接受
Is this preprocessor directive acceptable here?
拥有单顿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
的公共方法实际上会暴露出无关的实现细节。
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在 CPLEX 中求解线性规划,无需剪切和预处理
- 在海湾合作委员会中加快宏观预处理的任何方法
- Xmllint未设置,而在路径中找不到XMLLINT;跳过XML预处理
- 如何在预处理时读取文件
- 该预处理器指令在这里可以接受
- 在海湾合作委员会中欺骗预处理variadic宏
- 在经过预处理的C++代码中,#的含义是什么
- 如何在预处理时可靠地检测 clang 的版本
- 如何在大型项目中预处理具有多个 #include 文件的单个源文件
- 在程序中加入C/ c++之类的预处理能力
- 在编译时在c/c++预处理宏中验证参数为ARRAY类型
- 指针在c++预处理中的使用
- 在预处理条件中使用布尔字面值是否有效?
- 在预处理时间将sizeof()值转换为字符串
- 为什么C/C++预处理器在这里添加了一个空格
- 在经过预处理的svg-xml文档上设置QGraphicsSvgItem的呈现器非常慢
- 在 VC++ 2010 中使用 MSBuild 对文件执行自定义预处理
- 当宏用作变量名时,是否有任何方法可以跳过宏替换(在预处理期间)
- 在静态初始化列表之前预处理变量