-1

I'm making a C++ application that implements a Symbol class (similar to Atom in XLib or :symbols in ruby), which essentially maps a string to a unique-per-string integer value from a lookup table.

This means that initializing a Symbol is the only part of using one that takes any significant amount of time, searching through the lookup table each time one is created.

Usually that's just a necessary evil, but it becomes a pain when doing this:

void someRepeatedlyCalledFunction () {
    doThingWithSymbol(Symbol("HardCodedSymbolString"));
}

This means every time I call this function, the entire symbol lookup happens again.

Of course, this can be avoided via:

Symbol _HardCodedSymbolString;

void someRepeatedlyCalledFunction () {
    if (!_HardCodedSymbolString.isSet())
        _HardCodedSymbolString = Symbol("HardCodedSymbolString");

    doThingWithSymbol(_HardCodedSymbolString);
}

But this is an unattractive thing to have to do often, so ideally it could be hidden behind a macro - _SYMBOL(name) or something like that. The problem with this is that, because this macro would be called from within a function, there's no way of defining the global variable for that symbol.

Alternatively, it'd be even better if hardcoded symbol values were added to the list at compile-time, so the proper symbol values are put in like constants - but I see no way of doing this without writing some sort of custom preprocessor step.

Is there a way to implement these solutions, or perhaps a better solution?

Ethan McTague
  • 2,040
  • 3
  • 16
  • 47

1 Answers1

-3

You could make the variable static?

void someRepeatedlyCalledFunction () {
    static Symbol _HardCodedSymbolString;
    if (!_HardCodedSymbolString.isSet())
        _HardCodedSymbolString = Symbol("HardCodedSymbolString");

    doThingWithSymbol(_HardCodedSymbolString);
}

Alternatively, it'd be even better if hardcoded symbol values were added to the list at compile-time, so the proper symbol values are put in like constants - but I see no way of doing this without writing some sort of custom preprocessor step.

Should be easy enough to write a quick code generator (in whatever language you prefer)

robthebloke
  • 7,832
  • 6
  • 11