__FILE__ and __LINE__ again...

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Sep 10 09:44:06 PDT 2013


On Tue, Sep 10, 2013 at 06:00:53PM +0200, Paolo Invernizzi wrote:
> Johannes Pfau wrote something like this, in the logger thread:
> 
> >If you write code like this:
> >
> >void log(string file = __FILE__)() //A template
> >{
> >  logImpl(file);
> >}
> >void logImpl(string file){} //Not a template
> >
> >The compiler can always inline the log template. So there's no
> >template bloat as there will be effectively no instances of log.
> >Instead it will be inlined and logImpl will be called directly
> >just as if you manually called logImpl(__FILE__).
> 
> I'm trying something like that, but with __LINE__ in addition to put
> a little more pressure:
> 
>     void log(string file = __FILE__, int line = __LINE__)(){
> logImpl(file, line); }
>     void logImpl(string file, int line){}
> 
> I've then compiled a single file filled with 'log()', but I've found
> from 'nm' that the text section is still full of templated
> functions.
> 
> So the question is: is Johannes trick supposed to work, or there's
> something I don't understand well about template expansion and
> inlining?
[...]

Did you compile with dmd -inline?

Having said that, if you don't have variadic arguments, __FILE__ and
__LINE__ should be default arguments at the end of the *runtime*
argument list. Runtime arguments should be used to prevent template
bloat:

	void log(/* other arguments here */, string file=__FILE__, int line=__LINE__)
	{
		...
	}

If you have variadic arguments, though, this wouldn't work.

In any case, if the template function is just a thin wrapper around
logImpl, and you're compiling with -inline, then there should be no
runtime overhead. The compiler will still emit template instantiations
for each call to log(), but you can get rid of this with link-time
optimization (on Posix, you'd add -L-gc-sections to your dmd
command-line: this will cause ld to delete code sections that are never
referenced, which includes the log() instantiations if indeed they have
been inlined).


T

-- 
Arise, you prisoners of Windows 
Arise, you slaves of Redmond, Wash, 
The day and hour soon are coming 
When all the IT folks say "Gosh!" 
It isn't from a clever lawsuit 
That Windowsland will finally fall, 
But thousands writing open source code 
Like mice who nibble through a wall.
-- The Linux-nationale by Greg Baker


More information about the Digitalmars-d-learn mailing list