Wednesday, June 20, 2012

emulate virtual methods by templates


#include <iostream>
using namespace std;



template<typename T> struct D{
  void f(){cout<<"d::f"<<endl;}
  void g(){
    static_cast<T*>(this)->f();
  }
};



struct A:public D<A>{
  void f(){cout<<"A::f"<<endl;}
};

struct B:public D<B>{
};

int main(){

  A a;
  B b;

  a.g();
  b.g();

}

=====Output======
A::f
d::f

No comments:

Post a Comment