Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing certain code for every method call in C++

Tags:

c++

methods

I have a C++ class I want to inspect. So, I would like to all methods print their parameters and the return, just before getting out.

The latter looks somewhat easy. If I do return() for everything, a macro

#define return(a) cout << (a) << endl; return (a)

would do it (might be wrong) if I padronize all returns to parenthesized (or whatever this may be called). If I want to take this out, just comment out the define.

However, printing inputs seems more difficult. Is there a way I can do it, using C++ structures or with a workaroud hack?

like image 758
Luís Guilherme Avatar asked Mar 31 '10 12:03

Luís Guilherme


3 Answers

A few options come to mind:

  • Use a debugger.
  • Use the decorator pattern, as Space_C0wb0y suggested. However, this could be a lot of manual typing, since you'd have to duplicate all of the methods in the decorated class and add logging yourself. Maybe you could automate the creation of the decorator object by running doxygen on your class and then parsing its output...
  • Use aspect-oriented programming. (Logging, which is what you're wanting to do, is a common application of AOP.) Wikipedia lists a few AOP implementations for C++: AspectC++, XWeaver, and FeatureC++.
like image 107
Josh Kelley Avatar answered Nov 15 '22 19:11

Josh Kelley


However, printing inputs seems more difficult. Is there a way I can do it, using C++ structures or with a workaroud hack?

No.


Update: I'm going to lose some terseness in my answer by suggesting that you can probably achieve what you need by applying Design by Contract.

like image 45
Daniel Daranas Avatar answered Nov 15 '22 18:11

Daniel Daranas


It sounds like you want to use a debugging utility to me. That will allow you to see all of the parameters that you want.

like image 22
Seth M. Avatar answered Nov 15 '22 19:11

Seth M.