Making one struct work in place of another for function calls.

Andy Valencia dont at spam.me
Wed Apr 17 04:21:17 UTC 2024


On Wednesday, 17 April 2024 at 03:13:46 UTC, Liam McGillivray 
wrote:
> Is there a way I can replace "`TypeB`" in the function 
> parameters with another symbol, and then define that symbol to 
> accept `TypeB` as an argument, but also accept `TypeA` which 
> would get converted to `TypeB` using a function? I'm willing to 
> make a function template if it's rather simple.

Of course, if these were classes, this is classic inheritance and 
polymorphism.  It would be trivial to subclass the library's 
version and still have it accepted by things which knew how to 
use the parent class.  Or the library specified an interface, you 
could again use the polymorphism.

The closest I got was using function overloads, attached.

Andy

import std.stdio : writeln;

struct Foo {
     int x;

     void doit() {
         writeln(this.x);
     }
}

struct Bar {
     int y;

     // No doit()
}

void
myop(Foo f) {
     f.doit();
}

void
myop(Bar b) {
     auto f = Foo(b.y);
     f.doit();
}

void
main()
{
     auto b = Bar(3);
     b.myop();
}


More information about the Digitalmars-d-learn mailing list