Templates considered impressive

H. S. Teoh hsteoh at qfbox.info
Tue Oct 1 05:44:16 UTC 2024


On Tue, Oct 01, 2024 at 01:00:08AM +0000, Andy Valencia via Digitalmars-d-learn wrote:
> I had an old atoi() I wrote when I was getting started with D.  You know,
> fixed type, string in, int output.  Today for fun I templated the type:
> 
> T atoi(T)(string s)
[...]

It's all good and fun to try out how awesome D template programming, but
why spend the time and effort when you could have just done:

```
import std.conv;
string input = ...;
int i = input.to!int;
uint i = input.to!uint;
short s = input.to!short;
ushort us = input.to!ushort;
float f = input.to!float;
double d = input.to!double;
```

std.conv.to also automatically converts string to enum, handle narrowing
int conversions (by inserting runtime checks), alias itself away when
the target type implicitly converts from the source type (useful for
generic code to eliminate redundant conversions when you don't know the
input types), etc..

```
int i = 1234;
byte b = i.to!byte; // throws at runtime
short s = i.to!short; // OK, range check passes

enum E { a=10, b=20 }
E e = "a".to!E;		// returns E.a

string str = "abc";
string ss = str.to!string; // same as ss = str;

char[] ca = "abc";
ss = ca.to!string;	// same as ss = ca.dup;
```

Basically, unless you're one of those GC-phobes, std.conv.to is
literally your one-stop shop for all your type conversion needs.  You
can even extend it to work for your own custom types by defining the
requisite ctors and opCast overloads.  This is D, not C++, you shouldn't
need to write your own version of std.conv.to unless you have a *very*
good reason to.


T

-- 
Those who don't understand D are condemned to reinvent it, poorly. -- Daniel N


More information about the Digitalmars-d-learn mailing list