Template parameters that don't affect template type

Engine Machine via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 11 11:27:15 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?

Another good example is if something like

template X(bool ClearMemory = false)
{

}

ClearMemory would clearly not affect the type if it just clears 
memory that is malloc'ed, yet D would treat treat X!true from 
X!false.



More information about the Digitalmars-d-learn mailing list