Search code examples
d

Get current line of source file in D


Is there a way to get the current line in the source file you are on, like __LINE__ does in C++?


Solution

  • Yep, you can use __LINE__. Also, __FILE__.

    See Keywords section

    As BCS and Jonathan M Davis point out in the comments, there is a special case for __LINE__ and friends: when used as the default value of a template or function argument, they resolve to the location of the caller, not the signature of the template or function. This is great for saving callers from having to provide this information.

    void myAssert(T)(lazy T expression, string file = __FILE__, int line = __LINE__)
    {
         if (!expression)
         {
              // Write the caller location
              writefln("Assert failure at %s:%s", file, line);
         }
    }