@trusting generic functions
Lodovico Giaretta via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat May 28 05:55:38 PDT 2016
On Saturday, 28 May 2016 at 12:45:21 UTC, Era Scarecrow wrote:
> On Saturday, 28 May 2016 at 12:25:14 UTC, Lodovico Giaretta
> wrote:
>> The problem is that T is a type, and I should check for safety
>> of every method of T that I'm using in my function. This does
>> not scale well, and if I change the body of the function to
>> use a new method, I may forget to add it to the isSafe checks.
>
> I think i see what's going on then. Had to re-read it a few
> times. So ignore my previous reply.
>
>
>
> Easiest solution is to mark the entire struct as @safe or
> @trusted. Problem goes away (as long as you don't forcibly
> change it)
>
> Second is to force the check on the function before the call.
>
> static assert(isSafe!T.dosomething);
> pt.dosomething();
>
> Third... You could put in @safe code and have it complain?
> (might not work)
>
> @safe {
> pt.dosomething(); //if not @safe/@trusted it will refuse to
> compile
> }
>
> Fourth, you could create a helper function/template that
> cycles through a struct of your choice and tells you if any of
> it's methods fail to be safe. This will require a little more
> work, but it could be used as a full insurance and only
> requires a single template call on your function to ensure the
> safety.
>
> I can try and make this fourth one, but this isn't something
> I've done often.
Thank you for your answer.
I guess I'll got with overloading and if:
auto doSomethingDumb(T)(ref T t) @trusted
if (isSafe!(T.doSomething))
{
}
auto doSomethingDumb(T)(ref T t) @system
if (!isSafe!(T.doSomething))
{
}
The only annoyance is this:
auto doSomethingInRealLife(T)(T t) @trusted
if (isSafe!(T.doSomething1)
&& isSafe!(T.doSomething2)
&& isSafe!(T.doSomething3)
... and so on ...
{
}
auto doSomethingInRealLife(T)(T t) @system
if (!isSafe!(T.doSomething1)
|| !isSafe!(T.doSomething2)
|| !isSafe!(T.doSomething3)
... and so on ...
{
}
More information about the Digitalmars-d-learn
mailing list