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.

Kevin
  • 74,910
  • 12
  • 133
  • 166
go4sri
  • 1,490
  • 2
  • 15
  • 29
  • If you make map static it has to be initialized only once which doesn't look to be performance problem. – Rost Aug 21 '12 at 12:25
  • Possibly duplicate of http://stackoverflow.com/questions/138600/initializing-a-static-stdmapint-int-in-c – Rost Aug 21 '12 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. – Kevin Aug 21 '12 at 12:36

2 Answers2

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;
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
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.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173