mixins

Tejas notrealemail at gmail.com
Wed Nov 17 15:29:02 UTC 2021


On Wednesday, 17 November 2021 at 15:12:50 UTC, Tejas wrote:
> 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;
>> }
>> ```
>
> This good enough?
> ```d
> mixin template Validate(T)
> {
>     import std.stdio:writeln;
>     bool Validate(T a, T b){
>     	if(a > b)
>     	{
>        		writeln("invalid input");
>        		return false;
>     	}
>         else{
>             writeln("Valid input");
>             return true;
>         }
>     }
> }
>
> bool test(int a, int b)
> {
>     mixin Validate!(int);
>
>     /+----
>     on valid code
>     ----+/
> 	if (Validate(a,b))
>     	return true;
>     else
>         return false;
> }
>
> void main(){
>     test(100,300);
>     test(300,100);
> }
> ```


Wait a minute

You literally just want to template the entire function

Why are you using mixin templates?


```d
template Validate(T)
  {
      import std.stdio:writeln;
     bool Validate(T a, T b){
     	if(a > b)
   	{
        		writeln("invalid input");
        		return false;
     	}
        else{
              writeln("Valid input");
             return true;
          }
     }
}

void main(){
     Validate(100,300);
     Validate(300,100);
}
```

This is enough


More information about the Digitalmars-d-learn mailing list