Re: Bypass virtual function call when calling direcltly with a object/reference of that type?
Am 15.11.2010 21:10, schrieb Jamboree:
On 11???15???, ??????8???24???, Francis Glassborow
<francis.glassbo...@btinternet.com> wrote:
I am having great difficulty trying to decide why you would want to do that.
Note that you have to be using either a reference or a pointer for the late
binding to operate. If you use an actual object it will statically bind to the
function for the object's type. Always, no virtual mechanism involved.
Static binding is what I want here. I used to do static polymorphism
in C++, but things come that I have to combine the static and dynamic
ones,
for example:
type(A, B, C) are of polymorphic types which have virtual functions.
tuple<A, B, C> t;
t.get<0>().f() // f is declared as a virtual function, but we know
it's A::f definitely.
I just want to ask if I could make sure that the compiler will call
A::f without the virtual mechanism.
Though I think it really depends on the compiler implementation, but I
think modern compilers, especially Clang, should have ability to
figure that out.
In contrast to many other programming languages that support dynamic
polymorphism, this is quite easy in C++. Given C some base class
involved, just write
ra.C::f();
if ra is a reference or write
pa->C::f();
when pa is a pointer. This is guaranteed to suppress the virtual calling
mechanism as of 10.3/13:
"Explicit qualification with the scope operator (5.1) suppresses the
virtual call mechanism".
As long as you are writing correct code it will do the right thing. The only
time you need to be careful is if you are trying some fancy footwork changing an
objects type out of sight of the compiler.
I know it will do the right thing, but I just worried about if it
could do that efficiently.
Such as (pseudocode):
void dosomething(Base& b)
{
for (many times)
b.f(); // virtual function call
}
will f be called everytime through vptr->vtable?
Can we just buffer the exact function ptr that will be called?
If you write it this way, the semantics of above call signature is that
of a virtual dispatch each time. An implementation may decide either
way, but the observable behaviour must not change.
HTH & Greetings from Bremen,
Daniel Kr??gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]