www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Best Practice: Alternatives to Void Pointers

reply jsako <spam spam.com> writes:
The common C way to get a blob of generic data at runtime is to 
use void pointers like so:

struct Structo {
   int type;
   void* data;
}

Then cast the void pointer to whatever data you needed based on 
the type. I imagine D has a better mechanism for this sort of 
thing, but after some searching I couldn't find what is 
considered "best practice" for this application.

The obvious solution is to use objects and have polymorphism 
solve the problem, but if you want to avoid as much memory 
dereferencing as possible (say, to avoid cache misses), objects 
seem a poor choice since they are always reference variables.

So what's considered the best alternative to void pointers in D 
if you don't want to use objects? Make a tagged Union of all 
possible datatypes in the struct? Have a Byte array and cast that 
instead of a void pointer? Some sort of magic involving templates 
or other metaprogramming mechanisms?
Jan 30 2018
parent Simen =?UTF-8?B?S2rDpnLDpXM=?= <simen.kjaras gmail.com> writes:
On Tuesday, 30 January 2018 at 17:41:53 UTC, jsako wrote:
 So what's considered the best alternative to void pointers in D 
 if you don't want to use objects? Make a tagged Union of all 
 possible datatypes in the struct? Have a Byte array and cast 
 that instead of a void pointer? Some sort of magic involving 
 templates or other metaprogramming mechanisms?
https://dlang.org/phobos/std_variant.html -- Simen
Jan 30 2018