Re: Would Single Dispatch be a good start for C++17?
In article <5184f430$0$32116$14726298@news.sunsite.dk>,
demarcus_at_hotmail_com@tellus.orb.dotsrc.org (DeMarcus) wrote:
* Every class that needs to be streamed must have an accept()
function which is intrusive but even more disturbing boiler plate
code.
An alternative is to use dynamic_cast.
struct Visitor {
void visit( Shape *pShape ) {
if (Rectangle *pRect = dynamic_cast<Rectangle *>(pShape))
visit( *pRect );
else //... other shapes.
}
virtual void visit( Rectangle &rect ) = 0;
// ...
};
I try to avoid this because with my compiler, a dynamic_cast is a
lot slower than a virtual function call. However, some of my
colleagues prefer it because it's more flexible and less intrusive.
You can, for example, provide a syntax like:
visitor.registerReciever<Rectangle>();
visitor.registerReciever<Circle>();
that uses templates, dynamic_cast and overloading to dispatch only
to classes of interest.
* It's not trivial to provide arguments to that accept() function
since it has to be general for any kind of Visitor where all
visitors use their own arguments. The StreamVisitor above needs
the stream as a parameter while a DrawVisitor might need the memory
to draw to.
How do you provide Visitor arguments in your code?
In C++03, make them member variables of the visitor class. In C++11,
you could use lambdas instead.
Visitor visitor;
visitor.on<Rectangle>( [&]{ Rectangle &r ) {
os << r;
} );
visitor.on<Circle>( [&]{ Circle &c ) {
os << c;
} );
for (auto& shape : shapeVector)
visitor.visit( shape );
However, correct me if I'm wrong now, but what we do above is to
use only one virtual argument, so we only use /Single/ Dispatch.
Single Dispatch we already have in C++ with the normal virtual
methods so in order to implement Single Dispatch also for free
functions as we do above, we could simply use the virtual table we
already have.
Single dispatch is certainly simpler. However, with dynamic
linking we don't know until runtime how many slots we need in
the vtable, so we can't just use the vtable we already have.
I see that Single Dispatch for free functions could be a good start
to introduce Stroustrup et. al.'s Multimethods technique. What do
you think?
It's probably better to have one language change than two.
-- Dave Harris, Nottingham, UK.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]