CTFE & template predicates

Robert M. Münch via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 4 04:22:16 PDT 2015


On 2015-05-03 23:28:00 +0000, anonymous said:

> Here T would have to be a type. But you want to accept a string. So:
> ----
> template startsNotWith(string s,char c){
>      enum startsNotWith = s.length == 0 || s[0] != c;
> }
> ----

Hi, ok, just to better understand this (I have a C++ background (even 
quite old)): When I want to use some functions I need to specify the 
type? It's not possible to use T.length() which would compile if T is a 
string? I thought that it's just generic and I can throw in T.

>> 1. How do predicates get their argument(s)? I saw code where only the 
>> predicate was mentioned but no arguments. So, I assume there is some 
>> behind-the-curtain-magic going on. I read about things like "a == b" 
>> where I can reference 'a and 'b in a string.
> 
> Predicates are called/instantiated by the thing to which you pass them. 
> StaticFilter instantiates pred for each element of the T tuple it's 
> given. If some documentation doesn't say how the predicate will be 
> called/instantiated, then it's probably assumed to be obvious.

Well, and often it's obvious that it's not obvious ;-)

> String predicates are turned into functions behind the curtains. The 
> thing you instantiate with "a == b" turns it into `(a, b) {return a == 
> b;}` and uses that. I think we don't do string predicates for templates 
> like StaticFilter, though.

Ok, that helps to better understand how this works.

Thanks for the feedback.

-- 
Robert M. Münch
http://www.saphirion.com
smarter | better | faster



More information about the Digitalmars-d-learn mailing list