Template-style polymorphism in table structure

data pulverizer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Sep 4 07:07:54 PDT 2016


On Sunday, 4 September 2016 at 09:55:53 UTC, data pulverizer 
wrote:
> My main question is how to return GenericVector!(T) from the 
> getCol() method in the Table class instead of BaseVector.

I think I just solved my own query, change the BaseVector 
interface to a class and override it in the GenericVector(T) 
class:

----------------------------
class BaseVector{
     BaseVector get(size_t){
         return new BaseVector;
     };
}

class GenericVector(T) : BaseVector{
     T[] data;
     alias data this;
     override GenericVector get(size_t i){
         return new GenericVector!(T)(data[i]);
     }
     this(T[] arr){
         this.data = arr;
     }
     this(T elem){
         this.data ~= elem;
     }
     void append(T[] arr){
         this.data ~= arr;
     }

     override string toString() const {
         return format("%s", data);
     }
}

class Table{
// ... as before
}

void main(){
     auto index = new GenericVector!(int)([1, 2, 3, 4, 5]);
     auto numbers = new GenericVector!(double)([1.1, 2.2, 3.3, 
4.4, 5.5]);
     auto names = new GenericVector!(string)(["one", "two", 
"three", "four", "five"]);
     Table df = new Table(index, numbers, names);
     // now prints table.GenericVector!int.GenericVector
     writeln(typeid(df.getCol(0)));
}


More information about the Digitalmars-d-learn mailing list