On 2011-10-01 15:26, Steve Teale wrote:
Jacob,

So lets say I've got a result set from a database. I was thinking it would be 
tidy
and convenient if you could dress the result set up as a random access range, 
and
just pop the current row into a user defined struct without having to copy each
field, and was wondering if D had sufficient introspection to let me do this in 
a
way that was reasonably robust. If the compiler could tell me the names of the
struct fields and the offsets, then I could get the column names and types from
the database, and bingo! But it cant.

If you get a tuple of the values you want to set you can just do like this:

Struct s;
s.tupleof = values;

Nonetheless, I was experimenting, and then I noticed that the class TypeInfo
OffsetTypeInfo[] offTi() method does not return anything useful.

That might be understandable if TypeInfo applied only to classes. Derived 
classes
could make this method do something useful. But it doesn't - you can get an
instance for __all types__ via typeid. So the implementation in the runtime 
should
provide some sensible information for structs. Hence this thread.

I can get the field types and offsets using templates defined in std.traits and
std.typecons, but there's no way to get the names of the fields.

You don't need std.typecons or std.traits for that. You can get the field types using:

typeof(Struct.tupleof)

And you can get the names of the fields using a bit of tupleof and stringof magic. Have a look at:

https://github.com/jacob-carlborg/orange/blob/master/orange/util/Reflection.d#L212

You might find some other useful functions in that module as well.

However, I may still do it. The situation I'm considering is one where the
programmer is in charge and can make the call as to whether the convenience is
worth the risk. I can only protect her against type mismatches.

Steve


--
/Jacob Carlborg

Reply via email to