www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Faking a non-pure function as pure

reply =?UTF-8?B?Tm9yZGzDtnc=?= <per.nordlow gmail.com> writes:
I'm struggling with my definition of assumePure that should make 
a non-pure function `f` callable as pure `pureF`.

I've copied the definition of assumePure from the Phobos docs at

https://dlang.org/phobos/std_traits.html#SetFunctionAttributes

and managed to define pureF using it but I cannot call `pureF` as 
either

     auto x = (*pureF)(42);
     auto x = pureF(42);

How do I do that?

import std.traits : isFunctionPointer, isDelegate, 
functionAttributes, FunctionAttribute, SetFunctionAttributes, 
functionLinkage;

/** Return `T` assumed to be `pure`.
     Copied from 
https://dlang.org/phobos/std_traits.html#SetFunctionAttributes.
     */
auto assumePure(T)(T t)
     if (isFunctionPointer!T || isDelegate!T)
{
     enum attrs = functionAttributes!T | FunctionAttribute.pure_;
     return cast(SetFunctionAttributes!(T, functionLinkage!T, 
attrs)) t;
}

int f(int x)
{
     return x + 1;
}

void g() pure
{
     static assert(!__traits(compiles, { auto x = f(42); }));
     alias pureF = assumePure!(typeof(&f));
     // TODO: how do I call pureF?
     // auto x = (*pureF)(42);
     // auto x = pureF(42);
}
Feb 16 2018
parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 02/16/2018 09:58 AM, Nordlöw wrote:

 void g() pure
 {
      static assert(!__traits(compiles, { auto x = f(42); }));
      alias pureF = assumePure!(typeof(&f));
      // TODO: how do I call pureF?
      // auto x = (*pureF)(42);
      // auto x = pureF(42);
 }
 
auto pureF = assumePure(&f); pureF(42); Ali
Feb 16 2018
parent =?UTF-8?B?Tm9yZGzDtnc=?= <per.nordlow gmail.com> writes:
On Friday, 16 February 2018 at 18:03:40 UTC, Ali Çehreli wrote:
     auto pureF = assumePure(&f);
     pureF(42);

 Ali
Thanks!
Feb 17 2018