enumarray for better data arrays – EasyHack

In LibreOffice C++ code, there are many cases where developers have string literals that should be used in the code. If these are messages in the graphical user interface (GUI), they should be added to the translatable messages. But, there are many cases where the string literals has nothing to do with other languages, and they should be used as they are. In this case, enumarrays are helpful. Although they are not limited to string literals, and can be used for any data.

Using Symbolic Links

In old C code, using #define was the preferred way one could give a name to a string literal or other kinds of data. For example, consider this code:

const char[] FRAME_PROPNAME_ASCII_DISPATCHRECORDERSUPPLIER = "DispatchRecorderSupplier";
const char[] FRAME_PROPNAME_ASCII_ISHIDDEN = "IsHidden";
inline constexpr OUString FRAME_PROPNAME_ASCII_LAYOUTMANAGER = "LayoutManager";
const char[] FRAME_PROPNAME_ASCII_TITLE = "Title"_ustr;
const char[] FRAME_PROPNAME_ASCII_INDICATORINTERCEPTION = "IndicatorInterception";
const char[] FRAME_PROPNAME_ASCII_URL = "URL";

And also, the relevant states:

#define FRAME_PROPHANDLE_DISPATCHRECORDERSUPPLIER 0
#define FRAME_PROPHANDLE_ISHIDDEN 1
#define FRAME_PROPHANDLE_LAYOUTMANAGER 2
#define FRAME_PROPHANDLE_TITLE 3
#define FRAME_PROPHANDLE_INDICATORINTERCEPTION 4
#define FRAME_PROPHANDLE_URL 5

Although this C code still works in C++, it is not the desired approach in modern C++.

Using enumarray

In modern C++ code, you can use enumarry, which is defined in o3tl in LibreOffice. The above code becomes:

enum class FramePropNameASCII
{
    DispatcherRecorderSupplier,
    IsHidden,
    LayoutManager,
    Title,
    IndicatorInterception,
    URL,
    LAST=URL
};

And also, the string literal definitions:

constexpr o3tl::enumarray<FramePropNameASCII, OUString> FramePropName = {
    u"DispatchRecorderSupplier"_ustr,
    u"IsHidden"_ustr,
    u"LayoutManager"_ustr,
    u"Title"_ustr,
    u"IndicatorInterception"_ustr,
    u"URL"_ustr
};

The names are much more readable, as they do not have to be ALL_CAPPS, as per convention for symbolic constants in C. Their usage is also quite easy. For example, one can use [] to access the relevant string literal:

- xPropSet->getPropertyValue( FRAME_PROPNAME_ASCII_LAYOUTMANAGER ) >>= xLayoutManager;
+ xPropSet->getPropertyValue( FramePropName[FramePropNameASCII::LayoutManager] ) >>= xLayoutManager;

Final Notes

In LibreOffice, enumarrays are not limited to string literals, and they can be used with other data. This task is filed as tdf#169155, and if you like, you may try finding some instances in the code and modernize it using enumarrays.

Leave a Reply

Your email address will not be published. Required fields are marked *

I accept the Privacy Policy