Mix struct types in the same array

Paul Backus snarwin at gmail.com
Thu Dec 19 00:00:56 UTC 2019


On Wednesday, 18 December 2019 at 22:17:21 UTC, tirithen wrote:
> On Wednesday, 18 December 2019 at 22:11:10 UTC, Sebastiaan 
> Koppe wrote:
>>
>> If you know all types up front you can use the Sumtype library 
>> on code.dlang.org
>
> Thanks, it's a good starting point, the best would be if I only 
> needed to define that the struct would implement void 
> applyTo(ref User user) so that could be run in the loop to 
> update the User entity.

If all of the structs need to implement a particular method (or 
set of methods), you can use an interface and a templated adapter 
class to give them a common type. Here's a simple example:

import std.stdio: writeln;

struct User
{
     string name;
}

interface Action
{
     void applyTo(ref User);
}

class ActionAdapter(T) : Action
{
     T payload;

     this(T payload)
     {
         this.payload = payload;
     }

     override void applyTo(ref User user)
     {
         payload.applyTo(user);
     }
}

Action action(T)(T payload)
{
     return new ActionAdapter!T(payload);
}

struct SayHello
{
     void applyTo(ref User user)
     {
         writeln("Hello, ", user.name, ".");
     }
}

struct SayGoodbye
{
     void applyTo(ref User user)
     {
         writeln("Goodbye, ", user.name, ".");
     }
}

void main()
{
     Action[] actions = [action(SayHello()), action(SayGoodbye())];
     auto user = User("Joe Schmoe");

     foreach (action; actions)
         action.applyTo(user);
}


More information about the Digitalmars-d-learn mailing list