I am working on a transliteration tool. I have two lexer modules and a translator. Lexer generates tokens from the input text. Depending on the chosen language, I have to call the appropriate translation procedure.
I came up with a couple of ideas for this. First you need to create a base class called base_translator, and provide a virtual method ( translate()), which every translator must override. Now create a factory translator_factoryand call create()with the language name. This factory will return the corresponding instance.
But that sounds like engineering. So I came up with a different approach in which I have a structure similar to the following.
struct translator
{
const char* name;
void (*fp)();
};
Which only holds the language name and function pointer that can handle it. Use will be
static translator translators[] = {
{"first", first},
{"second", second}
};
const char* language = ;
for(int i = 0; i < 2; i++) {
translator *t = translators + i;
if(strcmp(t->name, language) == 0) {
t->fp();
break;
}
}
This approach is very simple and easy to maintain. But I wonder is this the best approach to the problem? Do you have any suggestions to make this better?
Any help would be great.
source
share