How can I do that in @nogc?

TheFlyingFiddle via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Feb 25 14:35:40 PST 2015


On Wednesday, 25 February 2015 at 19:32:50 UTC, Namespace wrote:
> How can I specify that 'func' is @nogc? Or can define the 
> function otherwise?

An alternative solution would be to use function
templated on an alias.

import std.traits;
void glCheck(alias func)(string file = __FILE__,
                          size_t line = __LINE__) @nogc
     if(isCallable!func)
{
     func();
     glCheckError(file, line);
}


void foo() { new int(5); } //Uses GC
void bar() @nogc { /* ... */ } //Does not use GC

unittest
{
     //Calling is a little different
     glCheck!foo; //Does not compile not @nogc
     glCheck!bar; //Works like a charm.
}


//If you wanted to take arguments to func
//it can be done like this.
void glCheck(alias func,
              string file = __FILE__,
              size_t line = __LINE__,
              Args...)(auto ref Args args) @nogc
      if(isCallable!func)
{
     func(args);
     glCheckError(file, line);
}

void buz(string a, uint b, float c) @nogc { /* ... */ }

unittest
{
    //Calling looks like this.
    glCheck!buz("foobar", 0xBAADF00D, 42.0f);
}



More information about the Digitalmars-d-learn mailing list