* Querejeto:
void main() {
Not valid.
why is that prototype not valid?
Because the standard says so. It's not valid for C, not for C++, and has
never been valid. The result type of 'main' must be 'int'.
Base &base = createInstance<Base>();
Not valid. Perhaps you meant
Base* base = createInstance<Base>();
Why are you requiring the method to return a pointer? I don't quite see
why a reference won't do. In fact, I could argue that it conforms to
the standard that references are always valid, while pointers could be
NULL.
OK, with the prototype & explanation you now supplied (snipped) it's
technically valid, sorry.
That sounds like there are cross-cutting concern that I would like to
extract from the class implementation
For general pre-call actions all you need is an ordinary smart-pointer
class. For general post-call actions the smart-pointer operator-> needs to
itself return a smart-pointer, where that operator-> result smart-pointer's
destructor (or a data member's destructor) does the post-call action.
However, while this works for simple logging, synchronization etc. you
cannot detect which member function is called because operator-> isn't told.
To do things on a per-member-function basis you need to use a wrapper that
offers the same external interface as Base, and forwards all calls to Base.
Such wrappers can be generated automatically by tools (use Google, perhaps
first to find the acronym for cross-cutting things, I always forget... ah,
aspect-oriented, first relevant hit and two links further, <url:
http://aosd.net/wiki/index.php?title=Tools_for_Developers>), or they can be
written "by hand"; in your case it's as simple as
class Derived: public Base
{
void constMethod() const
{
Logger log( whatever );
Base::constMethod();
}
void nonConstMethod()
{
Logger log( whatever );
Base::nonConstMethod();
}
};
where the constructor & destructor of Logger, which you must define to your
needs, does the logging work; here there's no "detection" of const or
non-const member function, but that information can be hardwired... ;-)
It's also possible to use more platform/compiler-dependent techniques that
within the constraint of a given platform are more general, e.g. COM-object
interceptors, but I'd advice against it.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?