Infer function template parameters

Jonas Drewsen jdrewsen at nospam.com
Fri Sep 21 12:29:42 PDT 2012


On Friday, 21 September 2012 at 15:04:14 UTC, Steven 
Schveighoffer wrote:
> On Thu, 20 Sep 2012 15:57:47 -0400, Jonas Drewsen 
> <jdrewsen at nospam.com> wrote:
>
>> In foreach statements the type can be inferred:
>>
>> foreach (MyFooBar fooBar; fooBars) writeln(fooBar);
>> same as:
>> foreach (foobar; fooBars) writeln(fooBar);
>>
>> This is nice and tidy.
>> Wouldn't it make sense to allow the same for function 
>> templates as well:
>>
>> auto min(L,R)(L a, R b)
>> {
>>     return a < b;
>> }
>>
>> same as:
>>
>> auto min(a,b)
>> {
>>     return a < b;
>> }
>>
>> What am I missing (except some code that needs chaging because 
>> only param type and not name has been specified in t?
>
> Although I like it, I wonder if it works in D's context free 
> grammar.  Timon probably would know best...
>
> I came up with this code, which compiles today:
>
> import std.stdio;
> alias int x;
>
> void foo(x) {}

This would not be a valid syntax in my proposal since x is not a 
parameter name as it should be, but a type name.

> void foo2(string x) {writeln(x);}
>
> void main()
> {
>     foo(1);
>     foo2("hello");
> }
>
> Under your proposal, if we shorten foo2 to foo2(x), what 
> happens?  Does it become just like foo?  Or does it turn into a 
> template?  Or is it an error?

A mentioned in the proposal (albeit not very clear) it requires 
non-templated function definitions to include both type and param 
names. If only one name is provided in a definition is always a 
param name. Unfortunately this is a breaking change for some code 
and that does speak against the proposal.

> Note that just because some syntax isn't valid doesn't mean it 
> should be utilized for a valid use.  That can result in code 
> compiling and meaning something completely different than you 
> expect.

I agree.




More information about the Digitalmars-d mailing list