Russell
Russell

Reputation: 4085

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.

This class will be created with something like.

SomeClassTemplate<A> infected_a(injected_function);

Upvotes: 2

Views: 166

Answers (2)

N_A
N_A

Reputation: 19897

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.

Upvotes: 1

Puppy
Puppy

Reputation: 146910

No, templates cannot generate that code for you automatically. You must write it by hand.

Upvotes: 4

Related Questions