June 01, 2006
Supporting Custom C++ TypesThe Problem: Supporting Additional Types
SOCI provides explicit template specializations of UseType and IntoType for the Standard C++ types short, int, char, unsigned long, double, char*, std::string, and std::tm.
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 (boost.org/doc/html/date_time.html) directly with SOCI, as in Listing Three.
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 tensif not hundredsof 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 presents the corresponding UML class diagram.
#include <boost/date_time/gregorian/gregorian.hpp> using boost::gregorian::months_of_year; using boost::gregorian::date;
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();.
|
|
||||||||||||||||||||||||||||||
|
|
|
|