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?

Jens
#include <cstddef>
#include <assert.h>

size_t inc() {
        static size_t val = 0;
        ++val;
        return val;
}

size_t bar(size_t num = inc()) {
        return num;
}

size_t line(size_t line = __LINE__) {
        return line;
}

int main() {
        int num = bar();
        assert(num == 1);
        num = bar();
        assert(num == 2);
        num = bar();
        num = bar();
        num = bar();
        assert(num == 5);

        // fails
        // I believe because __LINE__ is just a macro
        assert(line() == __LINE__);

        return 0;
}

Reply via email to