return val if

Mike Parker aldacron at gmail.com
Sun Mar 22 19:04:40 UTC 2020


On Sunday, 22 March 2020 at 18:48:32 UTC, Abby wrote:
> Is there a way to create a template that would do the same is 
> glib
>
> g_return_val_if_fail() 
> (https://developer.gnome.org/glib/stable/glib-Warnings-and-Assertions.html#g-return-val-if-fail)
>
> I was hoping something like this would work
>
> template returnValIfFail(alias expr, alias val)
> {
>     if(expr) return val;
> }

The documentation for the function reads:

"If expr evaluates to FALSE, the current function should be 
considered to have undefined behaviour (a programmer error). The 
only correct solution to such an error is to change the module 
that is calling the current function, so that it avoids this 
incorrect call."

Looks like the best approach in D would be to return val when 
expr is true and assert(0) otherwise. Also, you'll probably want 
the args to be available at runtime, else it would be a very 
restrictive template. Perhaps something like this?

```
T returnValIfFail(T)(bool expr, T val) {
     if(expr) return val;
     else assert(0);
}

void main() {
     import std.stdio : writeln;
     int y = 10;
     int x = returnValIfFail(y >= 10, 20);
     writeln(x);
}
```



More information about the Digitalmars-d-learn mailing list