C/C++

Supporting Custom C++ Types

By Stephen Hutton, June 01, 2006

Traits are a powerful technique that lets you create arbitrary user-defined types, among other things.

Of course, in practice, users will often prefer to work with other types, such as nonstandard String, Money, or Date classes. For example, if your development team has adopted the Boost libraries, you might like to use boost::gregorian::date ( which can be found at boost.org) directly with SOCI, as in Listing Three.

SOCI could of course be made to support boost::gregorian::date "out of the box," but that wouldn't solve the larger problem. One of the realities of C++ is that, for better or worse, there are tensif not hundredsof String, Numeric, and Date classes in widespread use.

Since the SOCI implementation is driven by template specialization, there is a natural way you could add support for your preferred custom type. For example, to add support for boost::gregorian::date, you could provide explicit specializations for UseType<date> and IntoType<date>, as in Listing Four.

Figure 2: Manually adding support for custom types.

In these example specializations, I've chosen to leverage the existing database access support for std::tm by having UseType<date> inherit from UseType<std::tm> and IntoType<date> inherit from IntoType<std::tm>.

A member variable value_ of type date holds a reference to the parameter, which is passed to into() and use(). In the case of IntoType<date>, the value_ data member is populated inside postFetch(), which is called by the framework after the database-related code is done executing.

Similarly, for UseType<date>, the value_ member is copied into StandardIntoType::data_ in preUse() before any database-related code executes. Because the parameter passed to the use() function can also be written to when used in conjunction with stored procedures, the value_ data member is also populated inside postUse();.

Traits, TypeConversion<T>, & Generalized Support for New Types

Adding support for new types in the manner just described is effective, but it requires you to have significant knowledge of the relevant library internals. After studying code that used the method in Listing Four, I realized that the implementation technique could be generalized. I therefore made several enhancements to the SOCI library to make defining new types simpler for library users. The key to the enhancements is a traits class called TypeConversion.

Defined in terms of its structure, a traits class is simply a class template, which contains only typedefs and static functions, and has no modifiable state or virtuals (see C++ Coding Standards by Herb Sutter and Andrei Alexandrescu, Addison-Wesley, 2004).

Nathan Meyers, who first introduced the traits concept, defines a traits class as: "A class used in place of template parameters. As a class, it aggregates useful types and constants; as a template, it provides an avenue for that 'extra level of indirection' that solves all software problems" (www.cantrip.org/traits.html).

Andrei Alexandrescu has written that traits are intended to "consolidate pieces of code that, depending upon a type...sport slight variations in terms of structure and/or behavior. To achieve this end, traits rely on explicit template specialization" (erdani.org/publications/traits.html).

There are three required class members for a valid TypeConversion trait class specialization:

The first step to add support for TypeConversion within the framework was to use the Template Method pattern (www.ddj.com/dept/cpp/184401436) by adding private virtual functions convertFrom() and convertTo() to classes StandardIntoType and StandardUseType. These new member functions are called from StandardUseType::preUse(),StandardUseType::post Use(), and StandardIntoType::postFetch().

I used the Template Method pattern here to isolate the code, which is unique to UseType and IntoType subclasses inside the convertFrom() and convertTo() private member functions. This simplifies the implementation of subclasses because they no longer need to include calls to their corresponding base class methods.

The next step was to partially specialize classes IntoType and UseType so that they inherit from IntoType<TypeConversion<T>::base_type> and UseType<TypeConversion<T>:: base_type>, respectively. These new classes also override convertTo() and convertFrom() and call TypeConversion <T>::to() and TypeConversion<T>::from().

An additional implementation detail is that these new IntoType and UseType specializations also inherit from the BaseValueHolder struct, which is used to hold the val_ member of type TypeConversion<T>::base_type. This ensures the correct order of initialization for the relevant member variables.

With the framework enhanced in this way, if you want to add SOCI support for boost::gregorian::date, you need only provide the appropriate TypeConversion specialization. IntoType<date> and UseType<date> are automatically generated by the compiler.

Compare this new method for adding custom types (Listing Six) to the old method (Listing Four). The obvious advantages are simplicity and separation of responsibilities. With the new method, you are not burdened with knowing the details of the SOCI implementation. The code that you need to provide to add support for a new type is isolated to the TypeConversion class template.

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task.
However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Video

This month's Dr. Dobb's Journal

This month,
Dr. Dobb's Journal is devoted to mobile programming. We introduce you to Apple's new Swift programming language, discuss the perils of being the third-most-popular mobile platform, revisit SQLite on Android
, and much more!