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?

Nordlöw
  • 11,838
  • 10
  • 52
  • 99
  • 1
    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? – beatgammit Jul 20 '13 at 19:06
  • 1
    Yes, please do so. Having many resolved questions marked as unanswered clutter the search results reduces the likelihood that question get answered quickly. – dnadlinger Aug 21 '13 at 07:51
  • Updated the question. Sorry for the delay. – Nordlöw Sep 08 '13 at 16:22

1 Answers1

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)
}
Peter Alexander
  • 53,344
  • 14
  • 119
  • 168