Instantiator Function for Bound template doesn't compile
Asked Answered
C

1

1

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?

Chinatown answered 6/7, 2013 at 11:51 Comment(3)
So, is this question solved then? If so, you can put your solution as an answer. If not, can you make your question more explicit?Fahland
Yes, please do so. Having many resolved questions marked as unanswered clutter the search results reduces the likelihood that question get answered quickly.Hairline
Updated the question. Sorry for the delay.Cranford
S
1

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)
}
Sweetie answered 9/9, 2013 at 12:45 Comment(1)
Aha. alias was key. Nice. Thx again Peter.Cranford

© 2022 - 2024 — McMap. All rights reserved.