C++ mechanisms for polymorphism
Explicit programmer-specified polymorphism
You can write f()
such that it can operate on multiple types in any of the following ways:
-
Preprocessing:
#define f(X)((X)+=2)// (note: in real code, use a longer uppercase name for a macro!)
-
Overloading:
void f(int& x){ x +=2;}void f(double& x){ x +=2;}
-
Templates:
template<typename T>void f(T& x){ x +=2;}
-
Virtual dispatch:
structBase{virtualBase&operator+=(int)=0;};struct X :Base{ X(int n): n_(n){} X&operator+=(int n){ n_ += n;return*this;}int n_;};struct Y :Base{ Y(double n): n_(n){} Y&operator+=(int n){ n_ += n;return*this;}double n_;};void f(Base& x){ x +=2;}// run-time polymorphic dispatch