Skip to main content

Posts

Showing posts from October, 2020

Abusing constexpr to implement gettext's _() macro with zero overhead.

You usually use the C library gettext with a _() macro that returns a localized version of the text passed in parameter. For example: puts ( _ ( "Hello" ) ) ; will result in a runtime search of the string "Hello", and _() eventually returns the localized version of the string. I assume the search is implemented using some sort of binary search, so it's probably extremely fast. It's fast, but we can get rid of the search altogether using constexpr functions! The trick is to use a constexpr function that  at compile time gets the ID of the given string. Then it's a matter of doing an array lookup in the table of strings for the desired locale. The array lookup is still unavoidable because we don't know at compile time which locale the app will use. In my case, _() is implemented using I18NStringIndex  which looks like this: constexpr bool I18N_EQ ( char const * a, char const * b ) { return std :: string_view ( a ) == b ; } constexpr int...