Is there an easy way in C++ to have a message lookup table that allows the use of variables.
For example in C you can have something like this:
const char* transaction_messages[] = {
"UNAUTHORIZED",
"UNKNOWN_ORDER",
"UNKNOWN_DEALER",
"UNKNOWN_COMMODITY",
"INVALID_MESSAGE",
"BOUGHT %d %s @ %f.1 FROM %s", //amount, commodity, price, dealer
"SOLD %d %s @ %f.1 FROM %s", //amount, commodity, price, dealer
"%d HAS BEEN FILLED", //order id
"%d HAS BEEN REVOKED", //order id
"%d %s %s %s %d %f.1 HAS BEEN POSTED", //order id, dealer, side, commodity, amount, price
"%d %s %s %s %d %f.1" //order id, dealer, side, commodity, amount, price
};
and then use it in a function like thislike this:
void myfunction(int amount, char* commodity, double price, char* dealer){
char *msg = transaction_message[6];
printf(msg, amount, commodity, price, dealer);
}
I want to be able to do the same with an ostream instead of having to do something with the << operator where the same thing would look like:
ostream << "BOUGHT" << amount << " " << commodity << " @ " << price << " FROM " << dealer;
the only way I can think of doing this right now would be to have a bunch of inline functions that return strings and instead of having a char* table instead have a function table that looks up the inline functions. There must be an easier way tho.
What you are doing is very similar to Localization (AKA L10N).
There are a couple of questions on this: Best way to design for localization of strings
But there are several packages that already deal with this.
These are basically designed to take all the strings from your application and package them in a separate resource (the correct resource (depending usually on locale) is selected at runtime). But they usually use the “English” (or should I say original text for non English programers) as the look-up text to find the correct resource string (thus the code is still readable to the developer) and the user gets a language specific string displayed.
Of course boost also has one
But there are others (A quick google finds)
Othere resources:
But getting the correct string is only half the battle. Then you need to correctly swap run-time values with place holders in the string. Personally this is where I think boost::format really shines.
Example:
The trouble is the order of nouns and verbs differ across languages. For example if we translate
into Azerbaijani
You will notice that the word for “Germany” (Almaniya) swaps places with the time. Thus the simple task of replacing items in a specific order does not work. What you need are indexed placeholders. (boost::format to the rescue).
Or more likely: