Template parameters that don't affect template type

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 11 13:43:13 PDT 2016


On Thursday, 11 August 2016 at 18:11:30 UTC, 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 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.
>
> Is there any way to get D to understand I want do not want a 
> template parameter to be part of the type comparison?
>
> 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!
>
> I guess D just can't handle it though?

It can be done, but you have to be explicit and should think very 
carefully if this is really a good design.

struct X(int defaultSize = 100)
{
     int size;
     int* p;

     void foo(int size)
     {
         size = max(size, defaultSize);
         p = cast(int*)malloc(size);
     }

     X opAssign(X2: X!n, int n)(X2 other)
     {
         //Do whatever you want here
     }

     X2 changeDefaultSize(int n)()
     {
         auto newX = X!n(n, p);
         p = null; //Release ownership of p

         return newX;
     }
}

void takesX50(X!50 x)
{
     //...
}

void main()
{
     X!100 n;
     X!100 m;
     X!50 o;

     n = m;
     o = m;

     takesX50(n); //Error
     takesX50(n.changeDefaultSize!50); //Okay
}

Really though this problem is properly solved by runtime 
polymorphism.


More information about the Digitalmars-d-learn mailing list