Design problem with respect to inheriting enums
I am building a framework where I need error checking for classes. I cannot use exceptions (not allowed). I decided to make a class that is inherited by all the classes that need error reports which has functions such as ReportError() [for the class itself] and GetError() [to get the last error - used by the caller] as well as functions to add custom errors called AddError(/* arguments */). The class has an enumerated type called FW_ERROR_TY开发者_Python百科PES with a few default error types which are the most common. For example, FW_ERROR_INIT (failed to initialize properly), FW_ERROR_CTOR (error during construction of the object) etc. When a class reports the error, an optional description can be added as well, which is logged (useful for later analysis to see what went wrong). This is all well and good, and works rather nicely for my purpose.
The problem comes when I want to add custom errors. The custom errors cannot be added as FW_ERROR_TYPES because the enum is not inherited by the class which is inheriting the error class. I did not forsee this problem while I was designing the error class. My original 'design' was that when GetError() is called to get the last error, it will return a FW_ERROR_TYPES, so a compiler error will be generated when used like so:
if (SomeClass->GetError()) // OR
if (SomeClass->GetError()) == true)
That is, it will force whoever is using it to specifically check against FW_ERROR_TYPES. When I found out that classes inheriting the error class cannot extend FW_ERROR_TYPES enum, I had to go with a generic enum and was forced to have GetError() return an unsigned integer. I defined the unsigned int as FW_ERROR_TYPE so that at least there is some indication that an error code is being returned.
Phew! So my question is, how can I improve on this design (or scrap it and go with a better one)? Is there a way to inherit enumerated types? I looked at codeproject site and found a rather complicated solution (if all else fails I will give that a go). Any help would be greatly appreciated.
Thanks!
You could have your error value be a class instead of an enum. You could have a base error class FwError
, with helpful methods like GetMessage()
, and then have a variety of error types inheriting from that base error class. When you have to check whether an error returned is a certain type of error, you can use Run-Time Type Information to check error types. If you need to create a new type of error, you can inherit from the base error class, or a more specific subclass. If a caller gets an error of a type it has never heard of, polymorphism ensures it can still handle it like a base FwError
and print a meaningful message.
Two (a 'little' complicated) solutions that I have found to this problem:
http://www.codeproject.com/KB/cpp/InheritEnum.aspx
http://www.codeproject.com/KB/cpp/ImprovedEnum.aspx
精彩评论