Constraining template with function signature
    Steven Schveighoffer via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Tue Jun  7 21:08:55 PDT 2016
    
    
  
On 6/7/16 9:42 PM, Carl Vogel wrote:
> Hi,
>
> What's the best way, when using a Callable as a template parameter, to
> constrain it by signature?
>
> For example, if you have a function that sorts an array like so:
>
> T[] sortArray(alias less, T)(T[] arr) { ... }
>
> Then you know that you'd want `less` to have signature (T, T) -> bool.
>
> Now, I can use something like isCallable std.traits to make sure the
> predicate is a Callable, and there are various function traits in the
> module that I could combine with `is` clauses to enforce the signature
> it seems, but that seems very clunky.  Is there a better way?
>
> I note that I don't find many examples of this in phobos, so I'm
> wondering if there actually is a good solution...
The de-facto way to do this is to write a lambda, and check that you can 
call the function inside the lambda, then check to see if that compiles.
e.g.:
if(is(typeof( { bool b = less(T.init, T.init)); } )))
The is(typeof( construct means "does this have a valid type". Should 
only work if the call is sound.
You can also use __traits(compiles, but for some reason Phobos writers 
prefer the is(typeof( mechanism (I remember someone saying there is a 
difference, but I don't know what it is).
-Steve
    
    
More information about the Digitalmars-d-learn
mailing list