Use template to simulate virtual functions first look at a simple virtual function example #include using namespace std; class b {public: void fun () {vf ();} Virtual void vf () {cout << "B: : vf "<< Endl;}}; class d: public b {public: void vf () {cout <<" D :: vf "<< endl;}}; int main () {d D; D.Fun (); B * pd = null; pd = & d; pd-> fun ();} It is also very simple, there is nothing to explain. D :: VF D :: VF Our goal is to use templates to re-implement it, the following is specific implementation: #include using namespace std; template Class base {public: void fun () {t * pt = static_cast (this); Pt-> vf ();} void vf () {cout << "Base :: vf" << endl;}}; class derived: public base { Public: void vf () {cout << "Drived: vf" << endl;}}; int main () {derived derived; derived.fun ();} its output: D :: vf Our template class Implement the virtual function! The key two statements are: class derived: public base t * pt = static_cast (this); the advantage of using templates is obvious: first is compiled after compiler, save VPTR and VTABLE. The second time efficiency, the template class has completed static binding during the compile period, which saves the call to the pointer to the pointer than the execution period of the virtual function. If the template is really powerful, I want to have a virtual function with a virtual function. Below we need to talk about its shortcomings: we re-write main () function int main () {derived derived; derived.fun (); base * pBase = & derived; pBase-> fun ();} seems no problem We recompile to execute ..................... I haven't reported wrong? The reason for the error is that the sharp brackets after the base class, you must declare that . We rewrite int Main () {derived deer; derived.fun (); base * pBase = & Derived; PBase-> Fun ();} Recompilated execution, if there is a problem. That is your own. The template is supported by default, so we can peek properly. Remote our base class.
Template (this); Pt-> VF ();} void vf () {cout << "Base :: Vf "<< endl;}}; but even so, angry brackets are also required. Int main () {derived derived; derived.fun (); base <> * pbase = & derived; pBase-> Fun ();} for more information and simulation of virtual function with template, please refer to http: // www. CodeProject.com/cpp/simulationofvirtualfunc.asp