Comment #0 by bearophile_hugs — 2014-11-13T10:42:15Z
You can convert 3 strings into a fixed-size array of length 3 using std.conv.to:
void main() {
import std.conv: to;
string[] data = ["1", "2", "3"];
auto foo = data.to!(int[3]);
}
So to simplify some code I'd like std.conv.to to support conversions to POD structs too (without constructors):
void main() {
import std.conv: to;
string[] data = ["1.5", "2", "3"];
static struct Foo { double a; uint b, c; }
auto foo = data.to!Foo;
}
That is similar to:
void main() {
import std.conv: to;
string[] data = ["1.5", "2", "3"];
static struct Foo { double a; uint b, c; }
auto foo = Foo(data[0].to!(typeof(Foo.tupleof[0])),
data[1].to!(typeof(Foo.tupleof[1])),
data[2].to!(typeof(Foo.tupleof[2])));
}
Similar code for std.typecons.tuples could be supported:
void main() {
import std.conv: to;
import std.typecons: Tuple;
string[] data = ["1.5", "2", "3"];
alias Foo = Tuple!(double,"a", uint,"b", uint,"c");
auto foo = data.to!Foo;
}
Comment #1 by bearophile_hugs — 2014-11-13T10:59:02Z
"data.to!Foo" is also more DRY, this helps avoid some bugs if later you change the definition of Foo.
Comment #2 by john.loughran.colvin — 2014-12-17T21:56:42Z
Why not non-POD structs and classes too?
Also, what do you think about situations where only a few of the members are set:
struct A { int a, b, c; }
auto a = A(3, 4);
is completely valid, but would you want to allow
auto a = [3, 4].to!A;
?
Comment #3 by bearophile_hugs — 2014-12-17T22:15:54Z
(In reply to John Colvin from comment #2)
> Why not non-POD structs and classes too?
To keep this Enhancement simple and well defined. Further extensions and enhancements are possible later.
> Also, what do you think about situations where only a few of the members are
> set:
>
> struct A { int a, b, c; }
> auto a = A(3, 4);
>
> is completely valid, but would you want to allow
>
> auto a = [3, 4].to!A;
>
> ?
Seems possible, but also adds complexity to the proposal, so better to keep things simple at first.
Comment #4 by robert.schadek — 2024-12-01T16:22:57Z