C++ 使所有类方法调用相同的函数
所以,我遇到了这种情况:C++ 使所有类方法调用相同的函数,c++,logging,methods,function-calls,C++,Logging,Methods,Function Calls,所以,我遇到了这种情况: #include "ActionLog.h" class Library{ ActionLog aLog; // ... the rest of it is private, mind you :D public: Library(...); void addBook(...); void removeBook(...); // ... aaand
#include "ActionLog.h"
class Library{
ActionLog aLog;
// ... the rest of it is private, mind you :D
public:
Library(...);
void addBook(...);
void removeBook(...);
// ... aaand there's a whole bunch of these :)
};
现在,classactionlog
有一个公共方法voidlog(…)代码>。一旦实现,它应该记录作为类库
方法列出的任何活动的开始(以及最终的成功/失败,这是可选的)
我想知道:是否有更优雅的方法使每个类库的方法调用aLog.log(…)代码>方法何时/之前开始执行?我所说的“优雅”是指除了在每个方法中显式调用它之外
我知道类似问题的解决方法,但我不熟悉Python,因此我甚至不确定是否适用与类相关的相同原则。C++没有任何内置的反射方法。既不能在运行时也不能在编译时列出方法。最好的办法是将日志隐藏到一些<代码>定义中的,用来定义每种方法,但是预处理器用法是现代C++中的反模式。
坚持当前的方法。正如polkovnikov.ph所说,如果没有反射,您将无法使用python的方法来实现这一点
只是为了好玩,我将把它留在这里,但我不推荐使用:
#include <iostream>
class Logger
{
public:
void log(std::string entry)
{
std::cout << entry << std::endl;
}
};
class A
{
Logger mylog;
public:
void foo()
{
std::cout << "Doing foo" << std::endl;
}
Logger& getLogger()
{
return mylog;
}
};
#define CALL_FUNC_AND_LOG(obj,func) \
{ obj.getLogger().log("Logging "#func); obj.func(); }
int main()
{
A a;
CALL_FUNC_AND_LOG(a,foo);
return 0;
}
#包括
类记录器
{
公众:
无效日志(标准::字符串条目)
{
std::这听起来确实是一个很好的案例来研究装饰器模式(我做了:),我想我可能会使用其中的一些想法来灵活地搜索库。谢谢。即使是当前的方法也依赖于\uuuu函数\uuuu
,作为区分类库的方法的帮助。。。
#include <iostream>
class Logger
{
std::string _entry;
public:
Logger(std::string entry)
{
_entry = entry;
std::cout << "Starting execution of " << entry << std::endl;
}
~Logger()
{
std::cout << "Ending execution of " << _entry << std::endl;
}
};
class A
{
public:
void foo()
{
std::cout << "Doing foo" << std::endl;
}
};
#define CALL_FUNC_AND_LOG(obj,func) \
{ \
Logger _mylogger(""#func); \
obj.func(); \
\
}
int main()
{
A a;
CALL_FUNC_AND_LOG(a,foo);
return 0;
}