Get calling this, if exists

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 24 11:17:57 PDT 2016


On 06/24/2016 10:19 AM, Smoke Adams wrote:

 > We have __FUNCTION__ so, __THIS__ seems somewhat natural. Null for
 > outside of objects is fine.

Would the following work, where you check the first argument?

import std.stdio;

void Log(string filename = __FILE__, T...)(T args)
{
     static if (is (T[0] == typeof(null))) {
         writefln("working without an object for %s", args[1 .. $]);

     } else static if (is (T[0] == class)) {
         writefln("working with object %s and %s", args[0], args[1 .. $]);

     } else {
         // Recurse
         import std.meta : AliasSeq;
         return Log!filename(AliasSeq!(null, args));
     }
}

class C {
}

void main() {
     Log(42, "hello");
     auto c = new C();
     Log(c, "cool");
     c.Log("breeze");
}

The output:

working without an object for 42
working with object deneme.C and cool
working with object deneme.C and breeze

Ali



More information about the Digitalmars-d-learn mailing list