Understand typeof trick

Joakim Brännström via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 25 04:10:41 PST 2015


Adam uses findSkip as an example and especially points out the "D 
idiom with is/typeof".

I'm not quite sure I understand it correctly. Please correct me 
if I have misunderstood anything regarding the idiom.

bool findSkip
   (alias pred = "a == b", R1, R2)
   (ref R1 haystack, R2 needle)
     if (isForwardRange!R1 &&
         isForwardRange!R2 &&
         is(                        [C]
            typeof(                 [B]
                   binaryFun!pred(  [A]
                                  haystack.front, needle.front))));

Nothing special. findSkip's pred is passed on to binaryFun. 
binaryFun's constraints thus apply to findSkip's pred.
See http://dlang.org/phobos/std_functional.html#.binaryFun

Evaluates to the function type "constructed" by binaryFun.

The is expression is true if A->B is valid "code".
It is used to convert any compiler errors to "false" (thus the 
constraint wouldn't be fulfilled).

I guess that binaryFun is used in the implementation of findSkip.
The reason for using this type of idiom is to avoid "compilation 
errors" to occur in the implementation when pred/R1/R2 is 
"funky". It "confuses" the user.
The idiom is thus used to move errors to the call site?
"D idiom: constraint error at call site"?

More information about the Digitalmars-d-learn mailing list