C++ does not allow dynamic dispatch based on argument types -- function overload resolution is always based on the static type of the expression. In your example, the static type of this
with always be A *
, even when it points at a B
, so your specialized function will never be called.
If you want dynamic dispatch, you must use a virtual function, and you can only dynamically dispatch based on the this
argument, never any other arguments. If you're worried about the overhead, you can hoist the dynamic call out of the loop and only call it once:
virtual bool local_policy() { return true; }
virtual void foo() {
bool policy = local_policy();
for (..) {
if (policy) {
/* do something */
}
}
}
The compiler can't ever do this optimization on its own, since it doesn't know that you'll never define a derived class that overrides the local_policy
function with something that has side effects...