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

Reply via email to