Preserving const? -- A potential solution

Tim M a at b.com
Sun Mar 8 01:16:19 PST 2009


Firstly option 2 was just crazy and I don't know why you said that. For  
option 1 you identifying the limitations and are just trying to apply as  
many problems as you can though the main barriers can easily be lowered.

As you already know templates are a compile time feature, so that  
statement about the compiler needs to every possible call doesn't make  
that much sense, the template inference works only for compile time type  
recognition and that is all that my sample code I posted used:



import std.stdio;

class A
{
       char[] name;
       this()
       {
             name = "A".dup;
       }
       T max(T)(T a, T b)
       {
             writefln(name ~ "- A.max()");
             return a > b ? a : b;
       }

}

class B : A
{
       this()
       {
             name = "B".dup;
       }
       T max(T)(T a, T b)
       {
             writefln(name ~ "- B.max()");
             return a > b ? a : b;
       }
}


void main()
{
       A b = new B();
       invariant int i = 2;
       invariant int j = 4;
       auto k = b.max(i,j); //invariant int is the only template compiled in

}

This code when run will print: B- A.max()

It is still a "B" but compiler can only see the "A.(T)max(T,T)" being  
called. What can actually be computed by the compiler is that another  
member function with the same exact signature exists in one or more  
subclasses. With this knowledge it can compile the "max" template as it  
did with "A" for all it's subclasses and insert the runtime type checking  
to decide which of them to call.

So just to help clarify the template is not instantiated in different ways  
but the same instantiation is done for each compatible class function.

The example currently compiles in:

A.max(invariant int)()

I am suggesting to compile in:

A.max(invariant int)()
B.max(invariant int)()
//any other subclasses

+ runtime type checking



More information about the Digitalmars-d mailing list