Getting around the non-virtuality of templates

Steven Schveighoffer schveiguy at yahoo.com
Tue Mar 27 08:46:19 PDT 2012


On Tue, 27 Mar 2012 11:26:08 -0400, Stewart Gordon <smjg_1998 at yahoo.com>  
wrote:

> On 27/03/2012 16:12, Stewart Gordon wrote:
>> On 26/03/2012 14:37, Steven Schveighoffer wrote:
>> <snip>
>>> So for now, I use the undocumented old-style functions. One other  
>>> thing that this
>>> "wrapper" method loses is covariance, which I use a lot in  
>>> dcollections. I haven't filed a
>>> bug on it, but there is at least a workaround on this one -- the  
>>> template can capture the
>>> type of "this" from the call site as a template parameter.
>>
>> I can't seem to get this to work at the moment:
> <snip>
>
> Just figured how to do it.
>
>      T method(this T)() {
>          return cast(T) this;
>      }
>
> Talk about having not got into D2 programming before....

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.  This will *not* work in  
an interface.  I'd argue the compiler should be aware of the special type  
of T for doing casts...

-Steve


More information about the Digitalmars-d mailing list