Adding invariant check to every method of a Class
I have a c开发者_StackOverflow社区lass with many methods and would like to check for pre/post conditions, such as is mMember == null and invoke function x() if not.
Is it possible to add pre/post conditions to every member of that class automatically? The class is defined in class.h and all methods are defined in class.cpp. Being able to define a macro at the start of the class.cpp would be ideal that would be inserted on every function entry in that file only.
I know I can manually add the same precondition/postcondition (using destructors) manually on every function entry but I keep running into this problem time and time again. This is not ideal as I can not check these changes in and must maintain them locally and they bit root from other people's changes.
I have not ever been able to do this in C++; I've always used a set of macros manually added to each member function.
It sounds like a job that might be well-suited to Aspect Oriented Programming, though, and I see that there are libraries out there for AOP in C++, such as AspectC++. It might be worth at least taking a look at one of these and seeing if it can be used to solve your problem.
精彩评论