Hoisting the dynamic type out of a loop (a.k.a. doing Java the C++ way)
I was discussing the merits of "modern" languages compared to C++ with some friends recently, when the following came up (I think inspired by Java): Does any C++ compiler optimize dynamic dispatch out of a loop? If not, is there any kind of construction that would allow the author to force (or strongly encourage) such an optimization? Here's the example. Suppose I have a polymorphic hierarchy: struct A { virtual int f() { return 0; } }; struct B : A { virtual int f() { return /* something complicated */; } /*...*/ }; Now I have a loop that accumulates f() : int acc(const A * p, unsigned int N)