Template parameter defaults

Jonathan M Davis jmdavisProg at gmx.com
Mon May 30 12:56:35 PDT 2011


On 2011-05-30 06:42, Johann MacDonagh wrote:
> I'm wondering if there's a cleaner way to do this:
> 
> class Test(T = uint)
> {
>      this(string s)
>      {
>      }
> }
> 
> void main(string[] argv)
> {
>      auto a = new Test!()("test");
> }
> 
> I'd *like* to be able to do this:
> 
> auto a = new Test("test");
> 
> and:
> 
> auto a = new Test!double("test");
> 
> The only possibility I see is to do this:
> 
> alias Test!() Test2;
> 
> But that introduces two types a user has to decide between. Any ideas?
> Am I out of luck here?

The alternative is to create a helper function outside of the class which 
calls the constructor. Unlike the class/struct, the function is able to use 
type inference, and so you can skip the !() part. For instance, that's what 
std.container.redBackTree does for RedBlackTree. In the case where you want a 
default argument, the function will use the default argument or you can give 
it the type directly. But you can't do that with a class/struct, because you 
don't get any type inference when instantiating a class/struct.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list