www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Instantiating Templates Structs with defaults parameter

reply d coder <dlang.coder gmail.com> writes:
Greetings

Kindly look at the code below. When I try to compile it with DMD 2-53, I get
an error:

foo.d(9): Error: struct template.Foo(int n = 1) is used as a type

It would be convenient if I am allowed to use Foo as a type without passing
parameters (with parameterized functions that is the default behavior). I
want to understand if not being able to instantiate Foo with default
parameters is a bug in DMD? Otherwise If it is not allowed in D2, I want to
know why such a limitation is there.

Regards
- Puneet

import std.stdio;

struct Foo(int n = 1) {
  public int value = n;
}

void main()
{
  Foo foo; // Does not compile
  // Foo!() foo; // This works
  writeln("Value is, ", foo.value);
}
Jun 09 2011
parent bearophile <bearophileHUGS lycos.com> writes:
d coder:

 It would be convenient if I am allowed to use Foo as a type without passing
 parameters (with parameterized functions that is the default behavior). I
 want to understand if not being able to instantiate Foo with default
 parameters is a bug in DMD? Otherwise If it is not allowed in D2, I want to
 know why such a limitation is there.
I think here DMD is working as intended, and I think this design is correc. This behaviour comes from uniformity: the ! (bang) is always required to instantiate a generic/struct/class/enum template. It's not required for function templates if the types can be inferred. Bye, bearophile
Jun 09 2011