@trusting generic functions
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun May 29 11:02:53 PDT 2016
On 5/28/16 7:50 AM, Lodovico Giaretta wrote:
> Let's say I have a generic function that uses pointers. It will be
> inferred @system by the compiler, but I know that the pointer usage can
> be @trusted.
> The problem is that if I declare the function @trusted, I'm also
> implicitly trusting any call to @system methods of the template parameter.
>
> Dumb example (pointer usage can be trusted, but doSomething may not):
>
> auto doSomethingDumb(T)(ref T t) // I want it @trusted if
> doSomething is at least @trusted
> {
> T* pt = &t;
> return pt.doSomething();
> }
>
> Is there any way around this? Any way to declare a function @trusted as
> long as the methods of the template argument are at least @trusted?
>
> Thank you in advance.
You can create a trusted expression by using a lambda and immediately
calling it. ag0aep6g brought it up.
I would write it like this (untested, but I think this works):
return (()@trusted => &t)().doSomething();
The key is to limit your code that is tainted by @trusted to as little
code as possible.
Note that doSomethingDumb will be inferred @safe and not @trusted. The
compiler should NEVER infer @trusted (for obvious reasons).
-Steve
More information about the Digitalmars-d-learn
mailing list