I'm extending a class hierarchy written in C# that implements a Visitor pattern (double-dispatch) using the dynamic keyword, as described here.
Here is some very simplified pseudo-code of what I'm currently doing in C#:
public class Command {
...
}
public class RunCommand : Command {
...
}
public class Base {
...
// Double-dispatch interface
public virtual void AcceptCommand(Command command) {
HandleCommand((dynamic)command);
}
// Example of a specialization that handles a RunCommand
protected virtual void HandleCommand(RunCommand command) {
...
}
}
Now, when I extend the hierarchy, derived classes may require handling new Command
specializations not known to the base class. In this case, the double-dispatch will fail (it seems as if dynamic overload resolution won't traverse the extended class hierarchy while trying to match a method). There is an easy fix for this (described in the previously linked article) and it consists in overriding the AcceptCommand()
method on the derived class (duplicating the original implementation), like this:
public class Derived : Base {
// Override to allow double-dispatch to handle commands introduced by Derived
public override void AcceptCommand(Command command) {
HandleCommand((dynamic)command);
}
}
Now, recently I required extending the hierarchy with classes from a project implemented in C++/CLI for convenience (a lot of interaction with unmanaged WIN32 API code). This project introduced several Command
specializations, so I need to override The AcceptCommand()
method in the C++/CLI class as I do in C# in order to fix double-dispatch, but the problem is I don't know how to perform the cast of the Command
object to a dynamic type in C++/CLI syntax. Is this something possible?