Hi, I currently have an enumeration in class Lexer:
- enum lexType {
-
-
/* token keywords */
-
lexIF, lexTHEN, lexWHILE, lexDO, lexBEGIN, lexEND, lexELSE, lexPROGRAM,
-
-
...
-
-
/* used for array iterations */
-
lexENUMSIZE
-
};
I have an array used to get the string representations of these types:
- const char* lexTypeNames[lexENUMSIZE];
This array is currently populated in the class's constructor:
- Lexer::Lexer() {
-
lexTypeNames[lexIF] = "lexif";
-
lexTypeNames[lexTHEN] = "lexthen";
-
lexTypeNames[lexWHILE] = "lexwhile";
-
lexTypeNames[lexDO] = "lexdo";
-
lexTypeNames[lexBEGIN] = "lexbegin";
-
lexTypeNames[lexEND] = "lexend";
-
lexTypeNames[lexELSE] = "lexelse";
-
...
-
}
Finally, I have a method in the class to retrieve the string representation given a lexType:
- const char* Lexer::getLexTypeName(lexType type) const {
-
return lexTypeNames[type];
-
}
The problem with this set up is that if another class has a lexType and I simply want to get the string representation of this lexType, I have to create a new instance of the Lexer class before I can call getLexTypeName(). Therefore, I was hoping there was some way to make getLexTypeName() static so I could simply call Lexer::getLexTypeName(lexType). I know I could do something like this:
- static const char* lexTypeNames[] = {"lexif", "lexthen", "lexwhile", "lexdo", ...};
However, this seems like a very error-prone solution that depends on the order of the enumerated elements for a correct initialization. Is there some way to statically initialize the array by manually specifying the indices like I did in the constructor? If not, is there a more elegant solution for this?
Thank you,
Brian