opIndex overload for slice not working...

biozic via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jan 24 23:07:38 PST 2016


On Monday, 25 January 2016 at 06:37:13 UTC, Enjoys Math wrote:
> class V(T) {
> public:
>    this() {}
>    V opIndex(size_t i, size_t j) {
>      writeln("Hello, foo!");
>      return this;
>    }
> }
>
> main() {
>    auto v = new V!int();
>    auto u = v[3..4];        // ERROR
> }
>
> Error:
> no [] operator overload for type the_module.V!int

You're mixing slicing and indexing. Use *opSlice* to support i..j 
slicing notation.

---
import std.stdio;

class V(T) {
public:
    this() {}

    V opIndex(size_t i, size_t j) {
      writeln("Indexing");
      return this;
    }

    V opSlice(size_t i, size_t j) {
      writeln("Slicing");
      return this;
    }
}

void main() {
    auto v = new V!int();
    auto w = v[3, 4]; // Indexing
    auto u = v[3..4]; // Slicing
}
---



More information about the Digitalmars-d-learn mailing list