On Tue, Dec 18, 2018 at 08:52:29AM -0500, Steven Schveighoffer via Digitalmars-d-learn wrote: > On 12/18/18 6:29 AM, Simen Kjærås wrote: > > On Tuesday, 18 December 2018 at 10:14:50 UTC, Per Nordlöw wrote: > > > What's the preferred way of creating a temporary @trusted scope > > > without writing a separate function? > > > > Jonathan's idea might also be encapsulated in a function, just like > > assumeUnique in Phobos: > > > > import std.stdio; > > > > template unsafe(alias fn) { > > @trusted auto unsafe(T...)(T args) { > > return fn(args); > > } > > } > > > > @system void fun(int n) { > > writeln("foo!"); > > } > > > > @safe unittest { > > unsafe!({ > > fun(2); > > }); > > > > unsafe!fun(2); > > } > > Wow, I really like this. The only real problem is that one generally > searches for @trusted when looking for unsafe code, but unsafe is > pretty obvious too. Also, args should be auto ref. > > Only thing better I can think of (for the second example) is to define > a prototype with the correct information, only with @trusted (and > specify the mangle). But any decent compiler should get rid of any > overhead there. [...]
I'm not so sure I like this. @trusted bits of code really should have a safe API that cannot be called in a way that breaks @safe. Being able to essentially "cast away" @safe for arbitrary bits of code seems to me to be a rather scary, underhanded way of undermining @safe. OTOH, if your function is very large and only isolated bits are non-@safe, then a construct like this one could help, by making the code less noisy, and ensuring that the other parts of the code still remain @safe. (Though IMO in such cases the function may be better refactored to encapsulate away the @trusted bits in functions with safe APIs, and keep the @safe code all in one place.) T -- MASM = Mana Ada Sistem, Man!