bytes (recordB).
Thoughts?
Template.
How? Dependent on what?
In my experience, this sort of problem is generally best handled
by an external code generator. Depending on the context, you
either define a very simple format, which you parse to generate
the C++ structs/classes and the SQL data base format, or you
extract the model from the data base, and parse it. The
generated code will contain not only the data members, but also
the SQL requests (or at least parts of them) needed to read and
write the data.
And in the case, you don't want to use an external tools, you can also
use macros. It is quite ugly but effective and you can then reuse the
files from project to project.
In a file, you define the structure of your rows:
RowFields.h:
/* TYPE | Name | CSV Header ... | SQL FIELD ....
SINT4 ( Id , "Id Number" )
UINT2 ( Foo , "Foo Value" )
STRING( Bar , "Bar name" )
....
And when you want to process the fields somewhere:
struct Row {
#define SINT4( _name, _header ) int32_t _name;
#define UINT2( _name, _header ) uint16_t _name;
...
#include "RowFields.h"
#undef ....
};
You can automate the common generation with another header files that
also performs the cleanup:
RowMacro.h:
#ifdef ROW_STRUCT_DEFINE
#define SINT4( _name, _header ) int32_t _name;
#define UINT2( _name, _header ) uint16_t _name;
..
#include ROW_FIELDS_FILE
#endif
And then:
struct Row {
#define ROW_STRUCT_DEFINE
#define ROW_FIELDS_FILE "RowFields.h"
#include "RowMacro.h"
};
The rule of thumb is to generate as less code as possible in the
macro, otherwise it is a hell to debug. I tend to generate only the
minimal structures with templated information and templated visitation
functions.
If your environment includes a compiler recent enough, you could
achieve the same with structs defining the fields and tuples for the
rows (except for switch-case, I have not found any technique to
emulate it).
--
Michael
You can use Composition instead of Inheritance. Instead of creating
RecordA and RecordB class. This would reduce coupling.