开发者

Can I use templates/macros/both to wrap each function of a C++ class?

开发者 https://www.devze.com 2023-04-10 21:27 出处:网络
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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消