Templated Interfaces?
Jason House
jason.james.house at gmail.com
Sun Aug 24 14:10:52 PDT 2008
Simen Kjaeraas wrote:
> On Sun, 24 Aug 2008 22:20:46 +0200, Benji Smith <dlanguage at benjismith.net>
> wrote:
>
>> Ary Borenszweig wrote:
>>> Benji Smith a écrit :
>>>> I've been trying to create a templated interface, and can't figure out
>>>> what I'm doing wrong. Here's the basic example:
>>>>
>>>> interface I(T) {
>>>> public T x();
>>>> }
>>>>
>>>> class C(T) : I(T) {
>>> class C(T) : I!(T) {
>>
>> Very nice! Thanks!
>>
>> Now let's say I want to create an array of those interface instances:
>>
>> interface I(T) {
>> public T x();
>> }
>>
>> class C(T) : I!(T) {
>> private T value;
>> public this(T val) { this.value = val; }
>> public T x() { return value; }
>> }
>>
>> void main() {
>> I!(char)[] array = new I!(char)[];
>> array ~ new C!(char)('a');
>> array ~ new C!(char)('b');
>> array ~ new C!(char)('c');
>> char value = array[0].x();
>> }
>>
>> Now the compiler is complaining about the line where I create the array.
>> It says "Error: new can only create structs, dynamic arrays or class
>> objects, not I[]'s"
>>
>> Obviously, I'm trying to create a dynamic array of interface instances,
>> so I'm not sure what I'm doing wrong.
>>
>> Thanks!
>>
>> --benji
>
> You do not need to initialize the the array with the "new I!(char)[]".
> Just use
>
> I!(char)[] array;
> array ~= new C!(char)('a');
> ...
> char value = array[0].x();
>
whoa, that's a bad idea!
You can not implicitly cast back and forth between interfaces and classes
that implement those interfaces; the underlying pointer is not the same.
There was a big discussion about this fairly recently on one of the D
mailing lists...
More information about the Digitalmars-d-learn
mailing list