I often want to define new ‘Exception’ classes, but need to have an appropriate constructor defined because constructors aren’t inherited.
class MyException : public Exception { public: MyException (const UString Msg) : Exception(Msg) { }; }
Typedefs don’t work for this, because they are simply aliases, not new classes. Currently, to avoid repeating this trivial boilerplate, I use a #define which does the donkeywork.
#define TEXCEPTION(T) class T : public Exception \ { \ public:\ T(const UString Msg) : Exception(Msg) {}; \ } ... TEXCEPTION(MyException);
But I keep wondering if there’s a better way of achieving this – maybe with templates, or some new C++0x feature
If you really want to have new classes derived from Exception, as opposed to having a template parameterized by a parameter, there is no way around writing your own constructor that just delegates the arguments without using a macro. C++0x will have the ability what you need by using something like
You can read about the details of that (seem to have quite a bit of extra rules) in 12.9 ‘Inheriting Constructors’ in the latest draft of C++0x.
In the meantime, i would recommend a policy based design (made small text, because the OP accepted the above, and not this policy stuff):