Function template declaration mystery...

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Feb 28 18:09:41 UTC 2018


On Wed, Feb 28, 2018 at 06:47:22PM +0100, Robert M. Münch via Digitalmars-d-learn wrote:
> Hi, I'm lost reading some code:
> 
> A a;
> 
> auto do(alias f, A)(auto ref A _a){
> 	alias fun = unaryFun!f;
> 	return ...
> 	...
> }
> 
> How is this alias stuff working? I mean what's the type of f? Is it an
> anonymous function which then gets checked to be unary? How is it
> recognized in the code using the function template?

Basically, the `alias f` is a catch-all template parameter that can
bind to basically anything that has a symbol. It's typically used to
bind to functions, delegates, and lambdas.

Technically, the function is missing a sig constraint that verifies that
f is in fact a unary function.  So it will fail to compile if you pass
something other than a unary function in.


> This function can be called with code like this:
> 
> a.do((myType) {...myCode...});

Are you sure the function name is 'do'? Because that's a keyword, and I
don't think it's a valid identifier.


> do(a, (myType) {...myCode...});

Are you sure this actually works?  Is there another overload that takes
a different parameter?  The overload with `alias f`, AFAIK, can only be
called with a compile-time parameter, like this:

	foo!((myType) { ... })(a);

	// or:
	a.foo!((myType) { ... });



> What's wondering me here is that the template function only has one
> paraemter (_a) but I somehow can get my myCode into it. But the code
> looks like a parameter to me. So why isn't it like:
> 
> auto do(alias f, A)(auto ref A _a, ??? myCode){...
> 
> I'm a bit confused.
[...]

Are you sure there isn't an overload that takes a second parameter?
Doesn't look like this will compile, given the above declaration.


T

-- 
Food and laptops don't mix.


More information about the Digitalmars-d-learn mailing list