www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Instantiating Templates Structs with defaults parameter

reply d coder <dlang.coder gmail.com> writes:
--00151747b3bcb6122004a5481d03
Content-Type: text/plain; charset=ISO-8859-1

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);
}

--00151747b3bcb6122004a5481d03
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

<div>Greetings</div><div><br></div><div>Kindly look at the code below. When=
 I try to compile it with DMD 2-53, I get an error:</div><div><div><br></di=
v><div>foo.d(9): Error: struct template.Foo(int n =3D 1) is used as a type<=
/div>

</div><div><br></div><div>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 instantia=
te Foo with default parameters is a bug in DMD? Otherwise If it is not allo=
wed in D2, I want to know why such a limitation is there.</div>

<div><br></div><div>Regards</div><div>- Puneet</div><div><br></div><div>imp=
ort std.stdio;</div><div><br></div><div>struct Foo(int n =3D 1) {</div><div=
=A0 public int value =3D n;</div><div>}</div><div><br></div><div>void main=

<div>{</div><div>=A0 Foo foo;<span class=3D"Apple-tab-span" style=3D"white-= space:pre"> </span> // Does not compile</div><div>=A0 // Foo!() foo; // Thi= s works</div><div>=A0 writeln(&quot;Value is, &quot;, foo.value);</div><div=
}</div>

<div><br></div> --00151747b3bcb6122004a5481d03--
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