How about "auto" parameters?

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri Jun 3 09:04:45 PDT 2011


On 6/2/11 10:16 PM, Mehrdad wrote:
> I just thought of something:
>
> The patterns
>
> 	auto foo1(T)(T arg) { /+ ... +/ }
> 	auto foo2(T...)(T args) { /+ ... +/ }
>
> are very common.
>
>
> Why not just supporting the syntax
>
> 	auto foo1(auto arg) { /+ ... +/ }
> 	auto foo2(auto args...) { /+ ... +/ }
>
> to make things easier?
>
> People can still say typeof(arg), typeof(args[0]), etc., just like
> before, but it's a lot easier (and cooler!) to have a code with all
> inferred types, rather than explicitly typed templates.
>
> Any ideas?

Walter and I were looking very seriously at this around the beginning of 
2008, with exactly the same syntax. At some point I recall we discussed 
a "static" version too.

That was just before we invented template constraints, and around the 
time when the discussion of C++ concepts were very intensively 
discussed. C++ concepts ended up not being adopted, but the discussions 
and past experience with C++ have revealed one important truth: you 
_almost never_ want a completely unconstrained template. Most any 
template (aside from the trivial identity function) wants to restrict 
the types it accepts. max() wants its parameters to be comparable. 
equal() wants its parameters to be iterable. map() wants its first 
argument to be a unary function that applies to the elements of the 
iterable second argument. And so on.

Even seemingly completely generic functions such as "to", which accepts 
most any type, are carefully specialized on type categories (classes, 
structs, enums, primitives, etc.) By the time all has been said and 
done, there are extremely few cases in which one ever wants to say "I'll 
take any argument here, and I don't care about its type". What we 
realized, therefore, was that such a feature would be usable very 
rarely, and furthermore it would simply encourage bad practice and 
sloppy programming (unrestricted templates are black holes that accept 
everything but then fail to compile with unintuitive error messages and 
loci).

(Cross one element off my wishlist: use "loci" at least once in 2011.)

Following the C++ concepts saga has helped us enormously. First, we 
realized that going that way would collapse D (as they nearly collapsed 
C++). Second, we figured we needed a simple, lightweight means to curb 
templates, and that's how restricted templates were born. It's one of 
our best ideas, and it has dramatically improved generic coding in D.


Thanks,

Andrei


More information about the Digitalmars-d mailing list