Mar 21, 2007 18:10
Here's a stupid trick I came up with to simplify implementations of the visitor pattern I'm using in an application I'm working on.
If you ignore the fact that it relies on nasty macros, it's pretty handy. Essentially, it lets me enforce that a visitor implements all the methods defined by the interface, without having to make the base class's methods abstract. This way I can assert at compile time that all my methods are defined, while still being able to use the base class as a sane 'default'.
As a result, if I add new methods to this interface and update the macro, the compiler immediately warns me about every single class that's missing an implementation. Likewise, if I want to change the signature (maybe by adding a new parameter) of the existing methods, I'll get a compile time error instead of the compiler silently adding an overload for the methods with incorrect signatures.
#define FAKE_CLASS(ClassName) \
namespace ClassName##Members { \
static void OnX (); \
static void OnY (); \
} \
\
class ClassName : public VisitorBase { \
inline void OnX () { \
ClassName##Members::OnX(); \
} \
inline void OnY () { \
ClassName##Members::OnY(); \
} \
}; \
\
namespace ClassName##Members
FAKE_CLASS(MyClass) {
static void OnX () {
}
static void OnY () {
}
}
c++,
code