I'm working on a C++ Project (Embarcadero C++ Builder) where many classes (all in the same namespace) need to get color values from color names. To realize that, I created a function getColorCode() used by all Classes, in a separate piece of code, Tools.cpp, shown below:
#include "Tools.h"
namespace mynamespace {
int getColorCode(std::string Name)
{
if (Name == "red") return(0xFF0000);
else if (Name == "green") return(0x00FF00);
else if (Name == "blue") return(0x0000FF);
// many more else ifs
else return(0x000000);
}
}
The header file is:
#ifndef MYNAMESPACE_TOOLS_H
#define MYNAMESPACE_TOOLS_H
#include <string>
namespace mynamespace {
int getColorCode(std::string Name);
}
#endif
This works, but I would like to have all color definitions stored in a map to avoid hundreds of else ifs. My problem is, that I cannot define something like std::map<std::string, int> ColorNames;in the header file of Tools.cpp without getting W8058 Cannot create pre-compiled header at the line defining the map. In addition, I get several linker warnings that mynamespace::ColorNames is defined in every Class including Tools.h.
What I planned was to fill the map at the first call to getColorCode() by checking map.empty() and add all the color names and codes to it, if it is empty, so further calls will just search the map.
Another try was creating a tools-class for this and initialize the map in the constructor. But then every class using it creates an own instance of it, which I do not want. Reading the discussions about singletons and trying the code proposed did not help.
Is there any practical way to implement this or shoud I stay with the ugly (non performant) if-then-else chain?
Thanks for any hints, Armin
If you can use C++11 (I'm not familiar with C++-builder), you can initialize a static map in the function like so
int getColorCode(std::string name) {
static std::map<std::string, int> colors{
{ "red", 0xFF0000 },
{ "green", 0x00FF00 },
// ... etc
};
// rest of logic.
}
The benefit of this is that the map is localized to the function, initialized once and only once, and cannot be accessed from the outside world.
If you don't have C++11 features (again, I don't know the compiler), simply check if the map is empty like you said, and fill it. I would still mark it as static though, global variables are bad.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With