templatesddmdrange-checking

Instantiator Function for Bound template doesn't compile


I'm trying to implement an instantiator function for my Bound template wrapper but I can't get it to work. I need this in order to convince people at work that we should switch from Ada to D.

I want this template

/** Bounded Value of Type T. */
struct Bound(T,
             T min = T.min,
             T max = T.max,
             bool Exceptional = true) {
...
}

to be instantiated as

auto x = bound!(0.0, 10.0)(1.0);

That is I want the first template argument T to be inferred by the values of the template parameters min and max. But how do I specify a template parameter with a default value?

Of course I could always do

auto bound(float min, float max, bool Exceptional = true)(float value) {
    return Bound!(float, min, max, Exceptional)(value);
}

but how do I make bound a template?


Solution

  • A little bit of a workaround, but this will work:

    import std.traits;
    
    template bound(alias min, alias max, bool Exceptional = true)
        if (!is(CommonType!(typeof(min), typeof(max)) == void))
    {
        auto bound(CommonType!(typeof(min), typeof(max)) value) {
            return Bound!(typeof(value), min, max, Exceptional)(value);
        }
    }
    

    And it works like this:

    void main()
    {
        auto a = bound!(0.0f, 2.0f)(1.0f);  
        auto b = bound!(0, 2)(1);
    
        import std.stdio;
        writeln(typeof(a).stringof); // Bound!(float, 0.00000F, 2.00000F, true)
        writeln(typeof(b).stringof); // Bound!(int, 0, 2, true)
    }