If I want to trigger an error in my interpreter I call this function:
Error( ErrorType type, Erro开发者_开发百科rSeverity severity, const char* msg, int line );
However, with that I can only output
Name error: Undefined variable in line 1
instead of
Name error: Undefined variable 'someVariableName' in line 1
I'm working entirely with strings (except for the error messages as they all are constant at the moment), so sprintf won't work.
- What is the best way to create an efficient error function that can output a constant message combined with a string that describes which object, e.g.: a non-existing variable, triggered the error?
This is C++, so you can overload your function with an extra parameter to provide the variable name. I would then use a std::stringstream to format the message. There is no need to worry about "efficiency" when reporting errors, as they should be rare and don't affect an application's overall performance.
use a macro branched on your error function that build your message.
example:
#define ERROR(var, msg) error(0, 1, #var " -> " msg, __LINE__)
#define WARNING(var, msg) error(0, 2, #var " -> " msg, __LINE__)
精彩评论