Functional and Delegated Literals in D

Reading TDPL on functions and delegated literals (5.6.1)

auto f = (int i) {}; assert(is(f == function)); 

I have an approval error. Is this statement correct?

I tried the following:

 int z = 5; auto f = (int i) { return i < 5; }; auto d = (int i) { return i < z; }; assert(is(typeof(f) == typeof(d))); 

The statement is really there. In fact, f is a delegate, not a function, even if it does not need a frame pointer to access local variables. This is mistake?

Also, I don't understand how assert(is(f == function)); must work.

I tried assert(is(f == delegate)); but this also failed. What's wrong?

I am using the DMD32 D v2.053 compiler

UPDATE

 auto f = (int i) {}; assert(is(typeof(f) == delegate)) 

It works correctly, although there is no reason to be a delegate

But

 auto f = function (int i) {}; assert(is(typeof(f) == void function(int))); // correct assert(is(typeof(f) == function)); // failed!!!!! 

Miracle It seems D2 is not yet ready for production.

+7
source share
2 answers

"f" is a variable. This expression compares types . This should work:

 assert(is(typeof(f) == delegate)); 

If you want to create a function instead of a delegate, you can use the function literal syntax:

 auto f = function (int i) { ... }; assert(is(typeof(f) == function)); // should be true 

If the literal function syntax is not used, the literal is considered to be a delegate (For expressions, see the section "Function literals" . Because D should not change the type based on whether the literal body needs a stack frame (this would be super-screw). EDIT: TDPL does indicate that the compiler will output the function instead of the delegate, if possible, regardless of the keyword “function.” This seems like a bad idea to me, so it might be something that was dropped.

As for why the function (f ==) doesn't work, it looks like a regression.

+5
source

You can find isFunctionPointer and isDelegate useful.

Update:

See this, taken from traits.d :

 template isSomeFunction(/ +@ @@ BUG4217@ @@+/T...) if (/ +@ @@ BUG4333@ @@+/staticLength!(T) == 1) { enum bool isSomeFunction = isSomeFunction_bug4333!(T).isSomeFunction; } private template isSomeFunction_bug4333(T...) { / +@ @@ BUG4333@ @@+/enum dummy__ = T.length; static if (is(typeof(& T[0]) U : U*) && is(U == function)) // T is a function symbol. enum bool isSomeFunction = true; else static if (is(T[0] W) || is(typeof(T[0]) W)) // T is an expression or a type. Take the type of it and examine. static if (is(WF : F*) && is(F == function)) enum bool isSomeFunction = true; // function pointer else enum bool isSomeFunction = is(W == function) || is(W == delegate); else enum bool isSomeFunction = false; } 

I think this may explain some things.

In other words:

 void main() { static if (is(typeof(&main) T : T*)) static assert( is(T == function)); static if (is(typeof(&main) U)) static assert(!is(U == function)); } 
+4
source

All Articles