I am using C++11. I am not allowed to use external libraries like boost etc. I must use STL only.
I have a number of events, which must be identified as string constants. I am not allowed to use enums or ints or any other data type. For example:
"event_name1"
"event_name2"
"some_other_event_name3"
"a_different_event_name12"
Then I have some classes which need to use these strings, but don't know the other classes exist (they don't have anything to do with each other).
class Panel{
void postEvent(){
SomeSingleton::postEvent("event_name");
}
}
Another class::
class SomeClass{
SomeClass(){
SomeSingleton::listenForEvent("event_name");
}
void receiveEvent(){
//This function is triggered when "event_name" occurs.
//Do stuff
}
}
All these events are constants, and are used to identify things that are happening.
Here is what I have tried:
How to store string constants that will be accessed by a number of different classes?
Some of the persons there suggested I provide specific details of how to solve a concrete problem, so I have created this new question.
How can I store the strings in a common file, so that all the other classes that use these strings can refer to the same file?
The easiest way would be to use a char const*
constant, as it's way more optimizable and don't use dynamic allocations.
Also you can use std::string_view
in the postEvent
function, avoiding dynamic allocations. This step is optional. If you cannot have string views and still want to avoid dynamic allocations, then refer to your implementation's SSO max capacity and keep event names below that size.
Also consider that nonstd::string_view
can be shipped as a C++11 library and most likely the abstraction you need. Library such as cpp17_headers
and string-view-lite
exist solely for that purpose.
It look like this:
constexpr auto event_name1 = "event_name1";
In a class as a static member it works the same way:
struct Type {
static constexpr auto event_name1 = "event_name1";
};
This will at most take space in the read-only static data of your executable.
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