Storing interfaces as void[]

David Zhang straivers98 at gmail.com
Fri Mar 12 19:24:17 UTC 2021


On Friday, 12 March 2021 at 18:50:26 UTC, tsbockman wrote:
> <snip>

The idea is to implement a service locator s.t. code like this is 
possible:

     // struct (I didn't mention this in the top post, my mistake)
     auto log = Logger()
     api_registry.register!Logger(log);

     // class/interface
     auto input = new InputReplay(recorded_input);
     api_registry.register!InputStream(input);

     //
     // somewhere else
     //

     // interface
     auto input = api_registry.get!InputStream();
     // do something with input.

     // struct*
     api_registry.get!Logger().info(...);

     //
     // and additionally
     //

     auto input = new KeyboardInput(...);
     api_registry.replace!InputStream(input);

> /* Fully qualified names can be *very* long because of 
> templates, so it can be wasteful to store and compare them at 
> runtime. Let's use `TypeInfo` instead: */

Aye, I'm using hashes. The idea is to support either D interfaces 
or structs with arbitrary content.

> `I` is *not* the type of an interface instance, it is the type 
> of a reference to an instance of the interface.

So `I i` is a reference to the instance, which itself holds a 
reference to the implementation, like a reference to a delegate 
(pointer to (ctx, fn))? Thus cast(void*) produces something like 
*(ctx, fn). I don't mind that. I just want to store that 
reference as void[], be able to replace with with some other 
reference to another implementation as void[], then retrieve that 
as a reference intact.

I don't really need to copy or move the class instances here, 
just be able to read, assign, and replace references to them in 
the same place that I read, assign, and replace void[]'s of 
structs.


More information about the Digitalmars-d-learn mailing list