to!() conversion between objects

Piotr Szturmaj bncrbme at jadamspam.pl
Thu Oct 20 01:22:38 PDT 2011


bearophile wrote:
> Piotr Szturmaj:
>
>>> Do you have some use case to show me?
>>
>> class C
>> {
>>       int i;
>>       string s;
>> }
>>
>> struct S
>> {
>>       string s;
>>       float f;
>> }
>>
>> auto c = to!C(S("5", 2.5f));
>> assert(c.i == 5&&  c.s == "2.5");
>
> This is an usage example, it isn't an use case.
> And it looks a bit messy.

Okay, as I said in other post it is only a complement to static 
tuple/struct mapping from ranges. Here are the use cases:

-- for SQL:

// conversion is used internally by db client implementation
auto result = sqlConn.query!S("SELECT 5, '2.5'");
auto row = result.front();
assert(row.s == "5" && row.f == 2.5f);

-- for CSV:

alias Tuple!(int, string, int) IdNameAge;

foreach (csvLine; csvFile.byCSVLine)
{
     auto line = to!IdNameAge(splitter(csvLine, ';'));
     // line here is a tuple converted from runtime csv fields
}

I'm going to argue that Phobos needs universal construction for handling 
static mapping of runtime data. This is done with runtime checks on 
field count and each field is converted using actual to!() functions. It 
may be used by database client writers.

Conversion function should look like this:

T toImpl(T, Range)(Range r)
{
     // TODO: converts to tuple, struct or class
}

The original toImpl posted by me is only a complement to the above. I 
think it may be helpful and avoid converting each field manually.


More information about the Digitalmars-d mailing list