ResGen: C++ Mode

Stephan Zuercher, February 18th, 2004.

C++ Resources

In practice, ResGen supports three modes of operation:

The main overview document concerns itself exclusively with ResGen's Java mode. This document explains how ResGen operates in C++ mode. See the section on the resgen ANT task for more information on selecting ResGen's mode.

ResGen's C++ mode uses the same properties files as Java mode. In addition it generates a header (.h) and source (.cpp) file for each resource bundle.

C++ framework

C++ mode requires that project using the generated resouces provide a framework for managing the messages given. The framework has the following requirements:

  1. The presence of a class named Locale in the same namespace as the generated resource files.
  2. The presence of a class named ResourceBundle in the same namespace as the generated resource files that may be used as a base class for generated resources.
  3. The presence of a class name ResourceDefinition in the same namespace as the generated resource files.
  4. The presence of this templated method:
    template<class _GRB, class _BC, class _BC_ITER>
    _GRB *makeInstance(
        _BC &bundleCache,
        const Locale &locale);
    

    The template's arguments are a class generated by ResGen in C++ mode (e.g. BirthdayResources in the examples below), a std::map<Locale, _GRB *>, and an iterator on that map.

    The method's purpose is to look up the generated resource bundle instance in the bundle cache for the given locale. If found, it should be returned to the caller. If not found, it should be instantiated for the locale, added to the map and returned. Normally, the method would also attempt to create an instance of the parent locale's bundle by calling itself recursively. For example, when instantiating a resource bundle for the "en_US" locale, one would also instantiate a bundle for the "en" locale and set it as a parent to the "en_US" locale. The "en" locale might have a nameless locale as its parent so that all message requests are guaranteed to be filled. This logic is controlled by the ResourceBundle class and need only be implemented if you wish locales to inherit messages from their parent locales.

An example of how to create a framework appropriate for ResGen C++ resources can be found in the Fennel project.

C++ exceptions

If exception resources are used (as opposed to just message resources), you will need to provide an exception class. A default exception class for all exception resources can be given (see <resourceBundle>, below), or you can override the default on a per-resource basis. The exception class must always have a basic constructor like this one:

Excn(const std::string &msg);

If chained exceptions are enabled for an exception resource, the exception class must also have a chained constructor:

Excn(const std::string &msg, const Excn * const chained);

C++ Example

The following examples assume you're familiar with the Java example given above.

Create a resource file

First, create a resource file like the following, BirthdayResource_en_US.xml:

<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="Resource.xsl" ?>
<resourceBundle
    locale="en_US"
    cppExceptionClassName="Excn"
    cppExceptionClassLocation="Excn.h">
  <message name="HappyBirthday">
    <text>Happy Birthday, {0}! You don''t look {1,number}.</text>
  </message>
  <exception name="TooYoung">
    <text>{0} has not been born yet.</text>
  </exception>
</resourceBundle>

Create ANT target

Now modify (or create) your ANT build-file, build.xml, as follows:

<taskdef name="resgen" classname="org.eigenbase.resgen.ResourceGenTask">
  <classpath path="lib/eigenbase-resgen.jar:lib/eigenbase-xom.jar"/>
</taskdef>

<target name="generate.resources">
  <resgen srcdir="source" locales="en_US">
    <include name="BirthdayResource_en_US.xml"/>
  </resgen>
</target>
</target>

I have assumed that your C++ source files are held in the "source" directory. I also assume that you'll write your own Makefile or equivalent to compile the code generated (BirthdayResource.h and BirthdayResource.cpp in this example).

Compile

Build as follows. (You need 'ant' on your path, and you will need to edit the project.classpath property in build.xml.)

$ ant
Buildfile: build.xml

generate.resources:
[resgen] Generating source\BirthdayResource.properties
[resgen] Generating source\BirthdayResource_en_US.properties
[resgen] Generating source\BirthdayResource.h
[resgen] Generating source\BirthdayResource.cpp

BUILD SUCCESSFUL

Total time: 3 seconds

Four files are generated.

source/happy/BirthdayResource.h:

// This class is generated. Do NOT modify it, or
// add it to source control.

/**
 * This class was generated
 * by class mondrian.resource.ResourceGen
 * from /BirthdayResource_en_US.xml
 * on Wed Feb 18 13:10:31 PST 2004.
 * It contains a list of messages, and methods to
 * retrieve and format those messages.
 **/

#ifndef Fennel_BirthdayResource_Included
#define Fennel_BirthdayResource_Included

#include <ctime>
#include <string>

#include "Locale.h"
#include "ResourceDefinition.h"
#include "ResourceBundle.h"

// begin includes specified by BirthdayResource_en_US.xml
#include "Excn.h"
// end includes specified by BirthdayResource_en_US.xml

using namespace std;

    /** HappyBirthday is 'Happy Birthday, {0}! You don''t look {1,number}.'     */
class HappyBirthday : public ResourceDefinition
{
  public:
  HappyBirthday(ResourceBundle *bundle, const string &key);

  string operator()(const string &p0, int p1) const;
};


    /** TooYoung is '{0} has not been born yet.'    */
class TooYoung : public ResourceDefinition
{
  public:
  TooYoung(ResourceBundle *bundle, const string &key);

  string operator()(const string &p0) const;
};


class BirthdayResource;
typedef map BirthdayResourceBundleCache;

class BirthdayResource : ResourceBundle
{
  protected:
  BirthdayResource(Locale locale);

  public:
  virtual ~BirthdayResource() { }

  static const BirthdayResource &instance();
  static const BirthdayResource &instance(const Locale &locale);

  static void setResourceFileLocation(const string &location);

  HappyBirthday HappyBirthday;

  TooYoung TooYoung;
  Excn* newTooYoung(const string &p0) const;

  template
    friend _GRB *makeInstance(_BC &bundleCache, const Locale &locale);
};

#endif // Fennel_BirthdayResource_Included

source/happy/BirthdayResource.cpp:

// This class is generated. Do NOT modify it, or
// add it to source control.

/**
 * This class was generated
 * by class mondrian.resource.ResourceGen
 * from BirthdayResource_en_US.xml
 * on Wed Feb 18 13:14:30 PST 2004.
 * It contains a list of messages, and methods to
 * retrieve and format those messages.
 **/

#include "BirthdayResource.h"
#include "ResourceBundle.h"
#include "Locale.h"

#include <map>
#include <string>

using namespace std;

#define BASENAME ("BirthdayResource")

static BirthdayResourceBundleCache bundleCache;
static string bundleLocation("");

const BirthdayResource &BirthdayResource::instance()
{
  return BirthdayResource::instance(Locale::getDefault());
}

const BirthdayResource &BirthdayResource::instance(const Locale &locale)
{
  return *makeInstance(bundleCache, locale);
}

void BirthdayResource::setResourceFileLocation(const string &location)
{
  bundleLocation = location;
}

BirthdayResource::BirthdayResource(Locale locale)
  : ResourceBundle(BASENAME, locale, bundleLocation),
    HappyBirthday(this, "HappyBirthday"),
    TooYoung(this, "TooYoung")
{ }

Excn* BirthdayResource::newTooYoung(const string &p0) const
{
  return new Excn(TooYoung.operator()(p0));
}

HappyBirthday::HappyBirthday(ResourceBundle *bundle, const string &key)
  : ResourceDefinition(bundle, key)
{ }

string HappyBirthday::operator()(const string &p0, int p1) const
{
  return format(p0, p1);
}

TooYoung::TooYoung(ResourceBundle *bundle, const string &key)
  : ResourceDefinition(bundle, key)
{ }

string TooYoung::operator()(const string &p0) const
{
  return format(p0);
}

source/happy/BirthdayResource.properties:

HappyBirthday=Happy Birthday, {0}! You don''t look {1, number}.
TooYoung={0} has not been born yet.

source/happy/BirthdayResource_en_US.properties:

# This file is intentionally blank. Add property values
# to this file to override the translations in the base
# properties file, BirthdayResource.properties.

For each resource, a member variable is generated in the generated class. The member variable allows you to use operator() to generate the resource's message with appropriate arguments substituted. In addition a newXxx() function is generated for each exception resource to retrieve an instance of that exception.

To obtain an instance of the resource bundle (e.g. BirthdayResource), use the static instance() or instance(const Locale &) methods. The former returns an instance for the default locale and the latter returns an instance for the given locale.

Tokens such as {0} and {1, number} in the message are automatically converted to method parameters of the right type. This means that if you ever change the parameters in your error message, or accidentally delete it, you code will no longer build. (If your code doesn't compile, you can fix the problem immediately; better that than getting a phone call, "I just got this really weird error...", in a few months time.)

Here's how you might use it in your code:

#include "BirthdayResource.h"

#include <iostream>
#include <string>

using namespace std;

void wishHappyBirthday(const string &name, int age) {
  if (age < 0) {
    throw BirthdayResource::instance().newTooYoung(name);
  }

  cout << BirthdayResource::instance().HappyBirthday(name, age) << endl;
}

int main(int argc, char **argv) {
  BirthdayResources::setResourceFileLocation("./");

  try {
    wishHappyBirthday("Fred", 33);
    wishHappyBirthday("Wilma", -3);
  }
  catch(Excn *x) {
    cout << "Exception: " << x->getMessage() << endl;
  }

  return 0;
}

This produces the following output.

Happy Birthday, Fred! You don't look 33.
Exception: Wilma has not been born yet.

In ResGen C++ resources, it is the framework's responsibility to handle switching from locale to locale.