import std.traits;
struct S {
int f() { return 1; }
int delegate() @nogc fAsNoGc() {
alias F = typeof(&f);
enum oldAttrs = functionAttributes!F;
return cast(SetFunctionAttributes!(F, functionLinkage!F, oldAttrs | FunctionAttribute.nogc))&f;
}
}
int moo() { return S().fAsNoGc()(); }
auto x = moo(); // CTFE, fails
void main() {
auto y = moo(); // runtime, succeeds
}
Comment #1 by eyal — 2017-06-09T20:11:57Z
I have a specific use-case:
assertOp!"<="(x, y);
I want x/y to be lazy so I can disable the assert at runtime (and avoid costs of computing x,y). I also want any exceptions computing x,y to be caught by assertOp.
I also need assert functions (including this one) to be @nogc but this is not directly supported due to (https://issues.dlang.org/show_bug.cgi?id=17486).
So I need to use a delegate cast to achieve the combination of @nogc and lazy params. This rules out any function that indirectly uses assertOp from ctfe, which is sad.
if(__ctfe) could skip the asserts altogether, but that loses a lot too.
Comment #2 by robert.schadek — 2024-12-13T18:52:33Z