Bug 4168 – More handy std.conv.to for std.algorithm.map
Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2010-05-09T07:48:00Z
Last change time
2015-06-09T05:13:48Z
Assigned to
nobody
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2010-05-09T07:48:51Z
Conversion of an array of strings to an array of integers is a common usage of map (for example the array of strings can come from the splitting of a line read from a text file), but this code doesn't work:
import std.algorithm: map;
import std.conv: to;
void main() {
auto number = to!int("10"); // OK
auto strings = ["10", "20"];
auto data = map!(to!int)(strings); // ERR
}
DMD 2.045 shows:
test.d(6): Error: template instance to!(int) does not match any template declaration
You must give both types to the to!, something that you usually don't need to give (see the 'number' variable in the first example):
import std.algorithm: map;
import std.conv: to;
void main() {
auto strings = ["10", "20"];
auto data = map!(to!(int, string))(strings); // OK
}
So to make to!() more handy when used with a map!() Phobos2 can define two to!
This is a test that shows how it can be done (here I have used the name 'foo' instead of 'to', but in std.conv it will keep its 'to' name):
import std.stdio: writeln;
import std.conv: to;
import std.algorithm: array, map;
template foo(Tout) {
Tout foo(Tin)(Tin x) {
return to!(Tout, Tin)(x);
}
}
Tout foo(Tout, Tin)(Tin x) {
return to!(Tout, Tin)(x);
}
void main() {
auto strings = ["10", "20"];
auto data = map!(foo!int)(strings); // OK
writeln(foo!int("10")); // OK
writeln(foo!(int, string)("20")); // OK
}