Alias sleep(int) for Thread.sleep(dur!("seconds")( int ));

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Nov 12 21:56:50 UTC 2019


On Tuesday, November 12, 2019 2:24:54 PM MST Marcone via Digitalmars-d-learn 
wrote:
> I am using this function to sleep, but I want a simple Alias. How
> can I alias this?
>
> // Function sleep(int)
> void sleep(int seconds){
>   Thread.sleep(dur!("seconds")( seconds ));
> }
>
> sleep(1); // Using function.

An alias just gives a different name for a symbol. It can't pass arguments
for you or call a function and pass its result to another. So, while you
could create an alias for Thread.sleep, you'd have to call it exactly like
you'd call Thread.sleep - just with a different name. If you want to do
something like have it accept an int instead of a Duration, then you need a
wrapper function like you're already doing.

Now, in core.time, dur!"seconds" has an alias named seconds, so if you're
simply looking to reduce how much typing you're doing, you could have
Thread.sleep(seconds(42)), or if you aliased Thread.sleep to sleep, you
could do sleep(seconds(42)), but you can't do something like sleep(42)
without a wrapper function.

In any case, I'd suggest that you avoid passing around naked integers as
time values. Thread.sleep takes a Duration specifically because it makes for
clearer code and is less error-prone than using a naked integer (since a
naked integer has no units).

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list