Template-style polymorphism in table structure

Lodovico Giaretta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Sep 5 01:41:52 PDT 2016


On Monday, 5 September 2016 at 06:45:07 UTC, data pulverizer 
wrote:
> On Sunday, 4 September 2016 at 14:49:30 UTC, Lodovico Giaretta 
> wrote:
>> Your getCol(i) could become getCol!T(i) and return an instance 
>> of GenericVector!T directly, after checking that the required 
>> column has in fact that type:
>>
>> GenericVector!T getCol!T(size_t i)
>> {
>>     if(typeid(cols[i]) == typeid(GenericVector!T))
>>         return cast(GenericVector!T)cols[i];
>>     else
>>         // assert(0) or throw exception
>> }
> I just realized that typeid only gives the class and not the 
> actual type, so the object will still need to be cast as you 
> mentioned above, however your above function will not infer T, 
> so the user will have to provide it. I wonder if there is a way 
> to dispatch the right type by a dynamic cast or I fear that 
> ZombineDev may be correct and the types will have to be 
> limited, which I definitely want to avoid!

ZombineDev is definitely correct, in that one thing is the static 
type, and another thing is the dynamic type. The type of a 
variable, or the return type of a method are based on the static 
type, computed at compile time. The "true" dynamic type is only 
available at runtime.

That's why I was showing you the use of tuples. If your code does 
not have branches that assign different column types, having the 
types statically determined as template parameters is the best 
choice.

If you really need dynamic types, then there's no alternative: 
the user must explicitly cast things to the correct dynamic type 
(my version of getCol is just a nice wrapper to do that). In 
fact, idiomatic D code tries to avoid dynamic types when 
possible, preferring templates.


More information about the Digitalmars-d-learn mailing list