Suppose I have C ++ code that looks like this:
class Base {
virtual void dummy() = 0;
};
class A : public Base {
public:
void f() { };
void dummy() {};
}
class B : public Base {
public:
void f() { };
void dummy() {};
}
template<class T1, class T2, class T3>
void doStuff(T1 &x, T2 &y, T3 &z) {
for (i=1; i<100000; ++i) {
x.f();
y.f();
z.f();
}
}
The goal is to avoid invoking virtual functions f()during this inner loop to allow compiler optimization. (This is obviously a simplified version of my real code. See this more specific question for more details on my use case. )
This works fine if the doStuffargument types are known at runtime, but if they are not, then this fails:
int main() {
Base *x = new A();
Base *y = new B();
Base *z = new A();
doStuff(*x, *y, *z);
}
to get around this (as suggested by this answer ), it seems to me that I should explicitly build a static dispatch function:
void doStuff(Base &x, Base &y, Base &z) {
A *a_x = dynamic_cast<A*>(&x);
B *b_x = dynamic_cast<B*>(&x);
A *a_y = dynamic_cast<A*>(&y);
B *b_y = dynamic_cast<B*>(&y);
A *a_z = dynamic_cast<A*>(&z);
B *b_z = dynamic_cast<B*>(&z);
if (a_x && a_y && a_z) {
doStuff(*a_x, &a_y, &a_z);
} else if (a_x && a_y && b_z) {
doStuff(*a_x, &a_y, &b_z);
}
}
, doStuff, , .
, : ? , - , , .