Just one time

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 20 08:55:44 PDT 2015


On Tuesday, 20 October 2015 at 15:48:47 UTC, Andrea Fontana wrote:
> It happens I need to perform an operation just one time (inside 
> a function, a loop...)
>
> I wonder if doing this it's a good idea or not.
>
> bool isFirstTime(alias T)()
> {
> 	static val = true;
>
> 	if (val)
> 	{
> 		val = false;
> 		return true;
> 	}
>
> 	return false;
> }
>
> So:
>
> void my_func()
> {
> 	if (isFirstTime!my_func) writeln("First call!");
> 	else writeln("Just another call");
> }
>
> myfunc(); // Print First call!
> myfunc(); // Print Just another call;
>
> Or (for example inside a for loop):
>
> assert(isFirstTime!"blah" == true);
> assert(isFirstTime!"blah" == false);
>
> Does it work as expected?

I think that's ok, because each unique (i.e. with a different 
parameter) instantiation of isFirstTime will have its own static 
val.

Be aware that there will be one instance of val per thread, so 
you are detecting the first run in each thread, not in the 
program overall.


More information about the Digitalmars-d-learn mailing list