Search code examples
c++c++11internationalizationlocalefacet

When and how to use std::locale::messages?


The C++ standard defines six categories of facets: collate, ctype, monetary, numeric, time, and messages.

I have known the usage of the first five, but I don't know when and how to use the last one: std::locale::messages.

Any illustrative examples?


Solution

  • std::locale::messages is used for opening message catalogues (most commonly GNU gettext) including translated strings. Here is an example which opens an existing message catalogue using on Linux (for sed) in German, retrieves (using get()) and outputs the translations for the English strings:

    #include <iostream>
    #include <locale>
    
    int main()
    {
        std::locale loc("de_DE.utf8");
        std::cout.imbue(loc);
        auto& facet = std::use_facet<std::messages<char>>(loc);
        auto cat = facet.open("sed", loc);
        if(cat < 0 )
            std::cout << "Could not open german \"sed\" message catalog\n";
        else
            std::cout << "\"No match\" in German: "
                      << facet.get(cat, 0, 0, "No match") << '\n'
                      << "\"Memory exhausted\" in German: "
                      << facet.get(cat, 0, 0, "Memory exhausted") << '\n';
        facet.close(cat);
    }
    

    which outputs:

    "No match" in German: Keine Übereinstimmung
    "Memory exhausted" in German: Speicher erschöpft
    

    Edit: Clarification according to this comment.