1

I am implementing a class that will handle the error messages for my application. The primary requirement for this class will be

  1. Store the error id to string mapping( during compile time)

    0, "No Error"

    147, "Invalid Input"

    . . .

    2500, "Unknown error"

  2. A method const std::string& getErrorString(int errorId) that will retrieve the string from the mapping

The errorIds are not contiguous, because I am going to assign ranges for modules. I was considering using a map to store the mapping, but this would mean that I would have to insert the error strings into the map at run-time - I am not sure if this is efficient, as all errors are available during compilation itself.

What is the best way to implement the error id to string mapping to allow for efficient retrieval and optimal run time? I do not have boost.

3
  • If you make map static it has to be initialized only once which doesn't look to be performance problem. Commented Aug 21, 2012 at 12:25
  • Possibly duplicate of stackoverflow.com/questions/138600/… Commented Aug 21, 2012 at 12:27
  • The twist to this problem is that multiple separate modules define their own error messages. If you cram every module's error messages into one code file, then it's not very modular! So ideally, you'd be able to do compile-time initialization, even if the mapping's data is spread throughout multiple files. Commented Aug 21, 2012 at 12:36

2 Answers 2

1

The dynamic initialization phase of your program startup is the ideal place for this:

std::map<int, std::string> const Errors {
  { 0, "No Error" },
  { 1, "Bad mojo" },
  /* ... */
  { 2500, "Unknown error" },
};

std::string const & getErrorString(int errorId)
{
    auto it = Errors.find(errorId);
    return it != Errors.end() ? it->second : Errors.find(2500)->second;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Depending on how many of them you have and how often you call the function, it may be easier to just have an array of structs with ints and const char *s and scan through it. Alternatively, you may split this array into ranges, though whether the performance gain worth the maintenance effort is up to you to determine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.