On Sunday, 23 December 2018 at 18:13:25 UTC, Vijay Nayar wrote:
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.

Hm... still not sure... ;)
This would compile and run:

´´´
import std.experimental.all;

size_t myHashFunction(int a) { return cast(size_t) a; }

void main()
{
        auto b = new B!(int, myHashFunction);
        b.arr = 42.iota.array;
        assert(b.find == 1);
}

class B(T, alias HashF)
{
        T[] arr;

        T find() const
        {
                foreach(el; arr)
                {
                        if(HashF(el))
                        {
                                return el;
                        }
                }
                assert(0);
        }
}
´´´

Reply via email to