How would you do this in D?

Jonathan M Davis jmdavisProg at gmx.com
Wed May 11 15:56:33 PDT 2011


On 2011-05-11 03:59, Don wrote:
> Jens Mueller wrote:
> > Jonathan M Davis wrote:
> >> On 2011-05-10 18:06, Jose Armando Garcia wrote:
> >>> Thanks. I should have read
> >>> http://www.digitalmars.com/d/2.0/template.html more carefully.
> >>> 
> >>> "Multiple instantiations of a TemplateDeclaration with the same
> >>> TemplateArgumentList, before implicit conversions, all will refer to
> >>> the same instantiation."
> >>> 
> >>> The default values which are evaluated at the call site are part of
> >>> the TemplateArgumentList.
> >> 
> >> Yes, default arguments are evaluated at the call site, not where the
> >> code is declared. I believe that C++ has the opposite behavior, so it's
> >> not uncommon that people miss that. It's _very_ useful though -
> >> particularly when dealing with __FILE__ and __LINE__.
> > 
> > I did some little testing (see attached file). The bar() example shows
> > that default arguments are evaluated at call site (even in C++). If it
> > was only evaluated when declared it would always return 1.
> > But __LINE__ does not work as in D. I believe that is due to __LINE__
> > being a macro in C whereas in D it is evaluated at instantiation time
> > (i.e. it is not text replacement). So it seems that instantiation of
> > default arguments is the same in D and C++. The difference is that
> > __LINE__ and __FILE__ are different things in C++ and D. In C++ there is
> > no such thing as evaluating __LINE__. Or let's say they are constant
> > expressions (due to textual replacement) where in D they are evaluated
> > differently depending on the context.
> > Does this make sense?
> 
> __LINE__ and __FILE__ are magical when used as default arguments in D,
> for exactly this use case, since it is *extremely* useful. In every
> other case they behave as in C++. (IIRC the magic is not even
> implemented for default arguments of __LINE__ + 0, only for __LINE__).

Hmm. Good to know. Well regardless of why and how it works with __FILE__ and 
__LINE__, it's definitely fantastic that they do. It is indeed _extremely_ 
useful.

- Jonathan M Davis


More information about the Digitalmars-d mailing list