I have code that calls H5TBmnake_table function to store an array of structs as a table in an HDF5 file. The function takes the following attributes of the struct as parameters
- the number of fields
- the fields' names
- their offsets
- their types
Since the standard C++ does not have introspection there is no straightforward way to retrieve these attributes programmatically without writing additional code.
To get around this limitation I created a template class StructInfo<typename>
with specializations which provide desired attributes for the structs I am working with. For instance, for a struct S
I could get the names of the fields by StructInfo<AStruct>.names
and so on. A self-contained example goes like
#include <hdf5.h>
#include <hdf5_hl.h>
struct S{
uint64_t a;
uint16_t b;
};
template<typename>
struct StructInfo {};
template<>
struct StructInfo<S>{
static constexpr unsigned int nfields = 2;
static const char *names[];
static const size_t offsets[];
static const hid_t types[];
};
const char *StructInfo<Trade>::names[] = {
"a",
"b"
};
const size_t StructInfo<Trade>::offsets[] = {
HOFFSET(struct Trade, a),
HOFFSET(struct Trade, b)
};
const hid_t StructInfo<Trade>::types[] = {
H5T_NATIVE_UINT_LEAST64,
H5T_NATIVE_UINT_LEAST16
};
Clearly, the code is hardly readable and quite boilerplate. How would you improve it?
Aucun commentaire:
Enregistrer un commentaire