mixins

Alexey animuspexus at protonmail.com
Mon Nov 22 05:52:35 UTC 2021


On Wednesday, 17 November 2021 at 14:51:58 UTC, Abby wrote:
> Hello I would like to create validation mixin or mixin template 
> which would return on error.
>
> Something like this:
>
>
> ```
> mixin template Validate(a, b)
> {
>     if(a > b)
>     {
>        writeln("invalid input");
>        return false;
>     }
> }
>
> bool test(a,b)
> {
>     mixin Validate!(a,b);
>
>     ----
>     on valid code
>     ----
>
>     return true;
> }
> ```

I'll add My 5 cents: with aliases this a little bit flexibilier, 
but without temporary function declaration this doesn't work

```D
import std.stdio;

mixin template validation(alias a, alias b)
{
	mixin(
		q{
			bool x(){
				writeln("a: ",a, " b: ", b);
				if (a > b)
				{
					writeln("invalid input");
					return false;
				}
				return true;
			}
		}
		);
}

bool test(int a, int b)
{
	mixin validation!(a, b);
	if (!x()) return false;
	return true;
}

void main()
{
     writeln("test result: ", test(2,1));
}
```


More information about the Digitalmars-d-learn mailing list