Struct multiple inheritance - another solution

Basile.B via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 27 14:31:58 PST 2015


I've read latest months several related topics (multiple alias 
this, super struct, etc). But the problem is that these solutions 
still differ from a real interface and they don't solve the 
problem of casting the interface at run-time (with arbitrary 
parameters).

I'll expose another approach.

Let's take the following declarations:

```
interface I {uint fun(uint a);}

struct S {uint fun(uint a);}
```

The problem will all know is that a structure doesn't allow 
multiple inheritance. So even if I and S members are compatible 
there is no way to extract an I from a S. The layout of a struct 
is different the one from a class: no virtual table. No really, a 
struct cannot have a virtual table.

But why the hell should it have one ? What's needed is just to 
return an I.
Since I really want an interface, the only way to return an I for 
S is that the stuff has to be class.

This is how it would look:

```
class SI : I
{
     void patch(void* instance)
     {
	//set fun_DG.ptr to instance, a pointer to a S.
	//set fun_DG.funcptr to address in memory of S.fun
     }

     uint delegate(uint) fun_DG;
     uint fun(uint a)
     {
	return fun_DG(a);
     }
}
```

Ok, but how this class has to be declared ? Should it be written 
for each struct and for each interface I'd like to extract from a 
struct ?

Fortunately no, D has metaprogramming features so we can imagine 
a simple function template that returns a string to mix, this 
string representing the class that implements an interface for a 
struct containing the methods that match to the interface.

And this works:

http://dpaste.dzfl.pl/50a8a7aa1267

And this is almost usable, except for the additional

```
void patch(void* instance);
```

that has to be added to each interface.


More information about the Digitalmars-d mailing list