templated type reduction
    EntangledQuanta via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Sat Sep  2 14:07:46 PDT 2017
    
    
  
Suppose one had the need to template a something like
struct X(T)
{
    string type = T.stringof;
    T t;
}
But one needs to get the type to know how to interpret X!T but 
one only has a void* to a type X!T. That is, we know it is an "X" 
but we don't know the specific T.
Now, this is easy as X!void or X!int or adding any specific but 
arbitrary type T, if the value we want is not dependent T... but 
in this case it is:
void* x = new X!int;
(passed around the program)
switch(x.type)
{
     case "int" : break;
}
which is invalid yet perfectly valid! Is there any way to make 
this work legitly in D? I could get the offset of the string then 
parse it, but that's a hack I'd rather not use and isn't really 
safe(change the order and it will break).
note that it is really no different from
struct X(T)
{
    string type = "asdf";
    T t;
}
in which we can do
string type = (cast(X!int)x).type; // = asdf
or
string type = (cast(X!float)x).type; // = asdf
but even this is a bit fishy.
Heres some code that does the offset hack:
struct X(T)
{
	string type = T.stringof;
	T x;
}
int main(string[] args)
{
	void* x = new X!int;
	int o = (X!float).type.offsetof;
	auto y = *cast(string*)(x + o);
	writeln(y);
	return 0;
}
    
    
More information about the Digitalmars-d-learn
mailing list