mixins
Paul Backus
snarwin at gmail.com
Wed Nov 17 16:04:30 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;
> }
> ```
Sadly this can't be done with a template mixin, because the body
of a template mixin is only allowed to contain *declarations*,
not *statements*.
However, it can be done with a string mixin:
```d
enum string Validate(string a, string b) = q{
if (} ~ a ~ q{ < } b ~ q{)
{
writeln("invalid input");
return false;
}
};
bool test(int a, int b)
{
mixin(Validate!("a", "b"));
// on valid code
return true;
}
```
The `q{...}` syntax is a [token string][1], a special kind of
string literal designed specifically for putting D code in a
string.
[1]: https://dlang.org/spec/lex.html#token_strings
More information about the Digitalmars-d-learn
mailing list