www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Covariance for []

reply davemo <zeforeg inboxbear.com> writes:
Hello, I was wondering why the following code does not compile.

```d
import std;

abstract class Range(T)
{
     abstract T back();
     abstract bool empty();
     abstract T front();
     abstract void popBack();
     abstract void popFront();
}

class RangeWrapper(TRange) : Range!(ForeachType!(TRange))
{
     alias TValue = ForeachType!(TRange);

     private TRange _range;

     this(TRange range)
     {
         _range = range;
     }

     override TValue back()
     {
         return _range.back();
     }

     override bool empty()
     {
         return _range.empty();
     }

     override TValue front()
     {
         return _range.front();
     }

     override void popBack()
     {
         return _range.popBack();
     }

     override void popFront()
     {
         return _range.popFront();
     }
}

auto wrap(TRange)(TRange range)
{
     return new RangeWrapper!TRange(range);
}

class A
{
}

class B : A
{
}

class C : A
{
     private B[] _bs;

     this()
     {
         _bs = [new B(), new B()];
     }

     Range!A as()
     {
         return wrap(_bs);
     }
}

void main()
{
}
```

I receive the following error.

```d
onlineapp.d(73): Error: cannot implicitly convert expression 
`wrap(this._bs)` of type `onlineapp.RangeWrapper!(B[])` to 
`onlineapp.Range!(A)`
```

Anyone have any idea how I can achieve 
[covariance](https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science
#Formal_definition) for `[]`?
Jan 19 2023
parent davemo <zeforeg inboxbear.com> writes:
On Thursday, 19 January 2023 at 12:54:39 UTC, davemo wrote:
 Hello, I was wondering why the following code does not compile.

 ```d
 import std;

 [...]
It looks like the following change works fine. ```d Range!A as() { return wrap(_bs.map!((b) { return cast(A) b; })); } ```
Jan 19 2023