如何确保类的每个方法都首先调用其他方法? [英] How to ensure that every method of a class calls some other method first?
问题描述
我有:
class Foo {
public:
void log() { }
void a() {
log();
}
void b() {
log();
}
};
有没有一种方法可以让每种方法 Foo
,调用 log()
,但无需我显式键入log()作为每个函数的第一行?
我想这样做,这样我就可以向每个函数添加行为,而不必遍历每个函数并确保进行了调用,并且还可以在添加新函数时自动添加代码。 ..
Is there a way that I can have each method of Foo
, call log()
, but without me having to explicitly type log() as the first line of each function ?
I want to do this, so that I can add behaviour to each function without having to go through each function and make sure the call is made, and also so that when I add new functions, the code is automatically added...
这甚至可能吗?我无法想象如何使用宏执行此操作,因此不确定从哪里开始...到目前为止,我唯一想到的方法是添加预构建步骤,以便在编译之前扫描文件并编辑源代码,但这似乎不是很聪明。...
Is this even possible ? I can't imagine how to do this with macro's, so not sure where to begin... The only way I have thought of so far, is to add a "pre-build step", so that before compiling I scan the file and edit the source code, but that doesn't seem very intelligent....
编辑:只是为了澄清-我不希望log()自己调用明显。它不需要成为课程的一部分。
Just to clarify - I don't want log() to call itself obviously. It doesn't need to be part of the class.
编辑:我更喜欢使用跨平台工作的方法,并且仅使用stl。
I would prefer using methods that would work cross platform, and using only the stl.
推荐答案
由于 operator->
的不寻常属性,我们可以在任何成员访问之前注入代码,但需要付出稍微弯曲的语法:
Thanks to the unusual properties of operator ->
, we can inject code before any member access, at the expense of a slightly bent syntax:
// Nothing special in Foo
struct Foo {
void a() { }
void b() { }
void c() { }
};
struct LoggingFoo : private Foo {
void log() const { }
// Here comes the trick
Foo const *operator -> () const { log(); return this; }
Foo *operator -> () { log(); return this; }
};
用法如下:
LoggingFoo f;
f->a();
这篇关于如何确保类的每个方法都首先调用其他方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!