June 01, 2006
Supporting Custom C++ TypesHow traits allow users to easily implement arbitrary types with the SOCI database libraryStephen Hutton
Traits are a powerful technique that lets you create arbitrary user-defined types, among other things.
Stephen is a Senior Software Engineer for Factor 5. He can be reached at www.featurecomplete.com.
Traits are powerful techniques with many applications to generic programming in C++. In this article, I use examples from the SOCI database library (soci.sf.net) to show how a simple TypeConversion traits class can be used to create an extensible framework that supports arbitrary user-defined types. The complete source code that implements this framework is available at http://www.ddj.com/code/.
SOCI is a database library with a minimalist syntax that mimics that of embedded SQL. (For more information, see "A Simple Oracle Call Interface" by Maciej Sobczak; www.ddj.com/184405930.) Listing One is a complete program that connects to a database (Oracle in this case), creates a table, inserts a row, and queries the table.
#include <soci.h> #include <iostream> #include <string>
Listing One
To use SOCI to insert (or update) data, you first declare and initialize variables of a type appropriate to the column into which you will be inserting. Then use the free function use() to bind the variables to placeholders in your SQL statement.
Similarly, to use SOCI to select data, you define variables of an appropriate type and pass them by reference to the free function into() to have them populated with the values returned by your select statement.
|
|
||||||||||||||||||||||||||||||
|
|
![]() |
||||
![]() |
|
|||
![]() |
||||
![]() |
||||
![]() |
|
|||
![]() |
|
|||