tags:

views:

217

answers:

4

I was wondering if I could do pre/post function call in C++ somehow. I have a wrapper class with lots of functions, and after every wrapper function call I should call another always the same function.

So I do not want to put that postFunction() call to every single one of the functions like this:

class Foo {
    f1();
    f2();
    f3();
    .
    .
    .
    fn();
}

void Foo::f1() {
    ::f1();
    postFunction();
}

void Foo::f2() {
    ::f2();
    postFunction();
}

etc.

Instead I want that postFunction call to come automatically when I call some Foo's member function. Is it possible? It would help maintenance..

+3  A: 

Sounds like a job for Aspect Oriented Programming using AspectC++

RichieHindle
Overkill. See jalf's answer below, using a temporary variable whose constructor and destructor are pre and post, respectively, is a very common and straightforward practice.
Not Sure
Conceptually I'd say yes, you're after aspect oriented programming, but going for a different (and non-standard) compiler just for this might be overkill
jalf
+4  A: 

Implement a wrapper that will take a function pointer as an argument, and will call pre\post function before the function call.

Foo::caller ( function* fp ) {
   preCall ();
   fp (...);
   postCall ();

}
Roman M
+2  A: 

As Richie pointed out, you're likely looking for Aspect Oriented Programming.

If that doesn't work for you though, another option you have is writing yet another wrapper class. Say instead of Foo, you have an interface named IFoo. You can then write a wrapper class to ensure the proper pre and post calls are used

class IFoo { 
public:
  void Bar();  
}

class FooWrapper: public IFoo {
public:
  FooWrapper( IFoo* pFoo ) {
    m_pFoo = pFoo;
  }
  void Bar() {
    PreBar();
    m_pFoo->Bar();
    PostBar();
  }
}
JaredPar
+9  A: 

Might be a case for RAII! Dun-dun-dunnn!

struct f1 {
  f1(Foo& foo) : foo(foo) {} // pre-function, if you need it
  void operator()(){} // main function
  ~f1() {} // post-function

private:
  Foo& foo;
}

Then you just have to make sure to create a new temporary f1 object every time you wish to call the function. Reusing it will obviously mean the pre/post functions don't get called every time.

Could even wrap it like this:

void call_f1(Foo& foo) {
  f1(foo)(); // calls constructor (pre), operator() (the function itself) and destructor (post)
}

You might experiment a bit with other ways of structuring it, but in general, see if you can't get constructors/destructors to do the heavy lifting for you.

Roman M's approach might be a good idea as well. Write one generic wrapper, which takes a functor or function pointer as its argument. That way, it can call pre/post functions before and after calling its argument

jalf