Best Way to Pass Template Typed Alias Parameters for Functions?

Vijay Nayar madric at gmail.com
Sun Dec 23 18:13:25 UTC 2018


On Sunday, 23 December 2018 at 18:04:32 UTC, Alex wrote:
> On Sunday, 23 December 2018 at 17:13:49 UTC, Vijay Nayar wrote:
>> I have a few cases where I would like to pass in a function as 
>> a value to a template, but I want to ensure that the function 
>> takes certain kinds of parameters, is a const function, or 
>> matches any other set of conditions.
>
> I assume you are looking for constraints...
> https://dlang.org/concepts.html
>
> Then, case B is the way to go, see
> https://run.dlang.io/is/jWU3tr
>
> Case D also looks promising. Not sure, how to formulate the 
> specialization right now...
>
> There are a lot of traits you can use for the constraints.
> https://dlang.org/phobos/std_traits.html
> and
> https://dlang.org/spec/traits.html
> e.g., for constness there is getFunctionAttributes, which could 
> be useful.

I've been playing with the idea of specifying the constraints or 
using "static assert" in the constructor. They are good options, 
but there's a few cases where they fall a bit short.  For 
example, imagine you have a container class that needs a 
comparator function to be able to compare the items in the 
container.  While you can use std.traits to assure the right kind 
of function is passed in, that information does not make its way 
into the type system.

For example, if you have a const function in your container like 
"T find() const", and this function needs to use that comparator, 
then you're out of luck because the compiler doesn't know that 
the comparator function is const and will not modify the objects 
being compared.

Last time I ran into this problem, my solution was simply to give 
up on const. But now I'm running into it again and trying to 
think through it again before giving up again.


More information about the Digitalmars-d-learn mailing list