contracts in interfaces

Yann skratchie at gmx.de
Fri Dec 14 00:11:39 PST 2012


Thanks for your reply!

>>  @property uint n();
> n() needs to be const:
>     @property uint n() const;

Ok. Why is that?

>> why does this produce a segmentation fault when executed:
> I don't know, you should show us a more complete minimal code 
> that shows the segfault.

Here you go (I stripped it down a bit too much the first time). 
Also, why does "new AdjacencyList(5)" not compile, even though 
Tdirected has a default value?

(I am very thankful for feedback of any kind about the following)

import std.algorithm;
import std.range;
import std.stdio;
import std.conv;
import std.string;

struct Edge
{
   this(bool exists = true)
   { _exists = exists; }
   bool _exists;
   alias _exists this;
}

interface Graph
{
   Edge opIndex(uint u, uint v)
   in { assert(u < n && v < n); }

   bool addEdge(uint u, uint v)
   in { assert(u < n && v < n); }
   //why does this line crash with Segfault 11 ?
   out(ret) { assert(this[u,v]); }

   @property uint n() const;
}

class AdjacencyListGraph(bool Tdirected = false) : Graph
{
   this(uint n = 0)
   { _adjList = new uint[][](n, 0); }

   Edge opIndex(uint u, uint v)
   {
     if(v < u && !Tdirected)
       swap(u, v);
     return Edge(countUntil(_adjList[u], v) >= 0);
   }

   @property uint n()
   { return cast(uint) _adjList.length; }

   bool addEdge(uint u, uint v)
   {
     if(v < u && !Tdirected)
       swap(u, v);
     if(this[u,v])
       return false;
     _adjList[u] ~= v;
     return true;
   }

   private uint[][] _adjList;
}

void main()
{
   //why do I have to add "!(false)", even though it's the default 
value?
   Graph g = new AdjacencyListGraph!(false)(5);
   g.addEdge(1,2);
}


More information about the Digitalmars-d-learn mailing list