Getting around the non-virtuality of templates

Stewart Gordon smjg_1998 at yahoo.com
Tue Mar 27 14:34:10 PDT 2012


On 27/03/2012 16:46, Steven Schveighoffer wrote:
<snip>
> One tip -- if you are doing method as above inside a class and not an interface, you can use:
>
> cast(T)cast(void*)this;
>
> which should avoid the unnecessary dynamic cast.

Which would work if the function always returns this.  But in the general case of what I'm 
using it for, it would call a virtual function that is meant to always return an object of 
the same class as this, but somebody could potentially create a subclass that breaks this 
rule.  But I suppose I could try comparing the .classinfo in an out contract to make sure 
it doesn't happen....

> This will *not* work in an interface. I'd
> argue the compiler should be aware of the special type of T for doing casts...

What's more, given the "this T" parameter it ought to automatically treat this as being of 
type T within the body of the function.  Essentially, semantically analyse the function 
when instantiated as a method of T rather than as a method of the class in which it is 
actually placed.

Stewart.


More information about the Digitalmars-d mailing list