Can I use templates/macros/both to wrap each function of a C++ class?
Suppose I had this.
class A {
public:
int f1();
int f2();
}
Is there any way to use templates/macros/both to generate a class that behaves like the following?
class GeneratedClass {
public:
GeneratedClass(InjectedFunction injected_function) { /* store it */ }
int f1() {
injected_function();
/* forward call to "inner class" and return its value */
}
int f2() {
injected_function()
/* forward call to "inner class" and return its value */
}
}
Basically I want to be able to generate a class that supports all the functions of a given class, but doing something before it blindly forwards the call开发者_StackOverflow中文版.
This class will be created with something like.
SomeClassTemplate<A> infected_a(injected_function);
No, templates cannot generate that code for you automatically. You must write it by hand.
It sounds like you want aspect-oriented C++. This link discusses implementing aspect-oriented C++ with pure C++ and also with a language extension.
See also here for an implementation.
Aspect-oriented programming is about separation of concerns in a project. Insertion points are specified where code is inserted. Sounds like exactly what you want.
精彩评论