Template parameters that don't affect template type

Engine Machine via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Aug 12 16:18:02 PDT 2016


On Thursday, 11 August 2016 at 20:43:13 UTC, Meta wrote:
> On Thursday, 11 August 2016 at 18:11:30 UTC, Engine Machine 
> wrote:
>> [...]
>
> 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.

Thanks. I am using templates and in some cases use template 
arguments to set compile time properties, hence runtime won't 
work.  These arguments don't affect the type itself, as far as 
the functionality/behavior as I use them.


More information about the Digitalmars-d-learn mailing list