Templated Interfaces?

Simen Kjaeraas simen.kjaras at gmail.com
Sun Aug 24 13:28:22 PDT 2008


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();

-- 
Simen


More information about the Digitalmars-d-learn mailing list