Template parameters that don't affect template type

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 11 11:46:33 PDT 2016


On 08/11/2016 11:11 AM, Engine Machine wrote:
 > I have the need, in some cases, to pass static information to a template
 > class but don't want it to affect its type.
 >
 > import std.algorithm, core.stdc.stdlib;
 > struct X(int defaultSize = 100)
 > {
 >    int Size;
 >    int* p;
 >    void foo(int size)
 >    {
 >     Size = max(size, defaultSize);
 >     p = cast(int*)malloc(Size);
 >    }
 > }
 >
 > If I do
 >
 > X!100 x;
 > X!100 y;
 > X!50 z;
 >
 > then I can do
 >
 > x = y;
 >
 > but not
 >
 > x = z;
 >
 > but of course D things these are completely different types.

The reason they are different types is the fact that the code generated 
for X!100 and X!50 are different. If x=z were allowed, which foo() would 
you expect to be executed for x.foo()? If it would change at run time 
depending on the actual type, we need a run-time expression, which 
cannot be a template parameter.

 > The type it
 > self does not depend on the default size.
 >
 > While one could argue that it can be unsafe, in the my context, it is 
not.

Understood but not possible with the template definition of D.

 > Is there any way to get D to understand I want do not want a template
 > parameter to be part of the type comparison?

It must involve runtime.

 > I use several parameters to pass info to the type that does not change
 > affect the type itself. It prevents the "same type" from being used with
 > "itself".
 >
 > another example:
 >
 > struct s(T1, T2)
 > {
 >     T1;
 > }
 >
 > then
 >
 > s!(int, double)
 >
 > and
 >
 > s!(int, float)
 >
 > should really be the same type! The fact that T2 is not used is 
important!

It's not used in this module but another module may be using __traits 
(or std.traits) to inspect that second argument.

 > I guess D just can't handle it though?

By design, no. (Another language that behaves this way is C++.)

Ali



More information about the Digitalmars-d-learn mailing list