Best way to make a template function conditionally @trusted

Paul Backus snarwin at gmail.com
Fri Apr 2 00:03:32 UTC 2021


On Thursday, 1 April 2021 at 22:35:01 UTC, tsbockman wrote:
> Suppose I have a templated struct member function for which I 
> can compute at compile-time when the function is memory safe, 
> and when it is not. But, the compiler cannot correctly 
> determine this automatically.
>
> What is the best way to express this in code? Other than 
> straight-up duplicating the implementation, the only answer 
> I've come up with so far is to create a `private @system` 
> implementation function, and then separate `public @system` and 
> `public @trusted` wrappers with appropriate template 
> constraints.
>
> Is there a better way?

Here's a technique I've used:

     // infer function attributes
     auto func(...)
     {
         // do your compile-time memory-safety check here
         enum bool shouldBeSystem = ...;

         static if (shouldBeSystem) {
             // force inference of @system
             cast(void) () @system {}();
         }

         () @trusted {
             // rest of code goes here
         }();
     }

As long as the compile-time check is correct, this is sound: the 
@trusted lambda can be called from @safe code if and only if 
`shouldBeSystem == false`.


More information about the Digitalmars-d-learn mailing list