Temporary @trusted scope

aliak something at something.com
Tue Dec 18 18:19:34 UTC 2018


On Tuesday, 18 December 2018 at 13:52:29 UTC, Steven 
Schveighoffer 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.
>
> -Steve

I've been gathering assume related stuff like this in a lib under 
an "assume" template. You can generalize further with multiple 
attributes inside a non-eponymous thing and use them like:

assume!fun.safe_(2);
assume!fun.nogc_(2);

I guess it's no very idiomatic D though, but I feel it reads 
better ... ok well maybe 🤷‍♂️: 
https://aliak00.github.io/bolts/bolts/assume/assume.html

Easier to be more specific with searches for "assumeSafe" instead 
of just "assume!" though.

Cheers,
- Ali




More information about the Digitalmars-d-learn mailing list