Overloading free functions & run-time dispatch based on parameter types

Robert M. Münch via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 5 02:54:27 PST 2016


>From the docs:

class A { }
class B : A { }
class C : B { }
void foo(A);
void foo(B);

void test()
{
    C c;
    foo(c); // calls foo(B)
}


I need the other way around. So, at runtime I get an A and depending on 
it's dynamic type, I would like to get the correct foo() called.

class A { }
class B : A { }
class C : A { }
void foo(B);
void foo(C);

void test()
{
    B b;
    A a = b:

    foo(a); // should call foo(B)
}

When doing something like this in my code I get the following compile 
error (message adapted to match pseudo-code):

source/app.d(751): Error: None of the overloads of 'foo' are callable 
using argument types (A), candidates are:
source/app.d(742):        app.foo(B)
source/app.d(746):        app.foo(C)

I hope the problem is understandable.

Is there a way to dispatch a call to the correct free functions based 
on the run-time type of the arguments without writing a switch or so?

-- 
Robert M. Münch
http://www.saphirion.com
smarter | better | faster



More information about the Digitalmars-d-learn mailing list