/* File: oop5.cpp Returning a callable object is more awkward, since we must return an Int2Int reference or an Int2Int pointer. */ #include using namespace std ; //------------------------------------------- class Int2Int { public: virtual int operator() (int) = 0 ; // pure virtual } ; //------------------------------------------- class AddX : public Int2Int { private: int m_offset ; public: AddX(int offset = 0) { m_offset = offset ; } int operator()(int m) { return m + m_offset ; } } ; //------------------------------------------- class Mult3 : public Int2Int { public: int operator()(int m) { return 3*m ; } } ; //------------------------------------------- class IncX : public Int2Int { public: int operator()(int n) { return n+1 ; } } ; //------------------------------------------- void apply(Int2Int& f, int A[], int n) { for (int i=0 ; i < n ; i++) { A[i] = f( A[i] ) ; } } //------------------------------------------- Int2Int& select(int n) { static AddX add3(3) ; // really should be const static AddX add5(5) ; static Mult3 times3 ; static IncX finc ; switch (n) { case 0 : return add3 ; case 1 : return add5 ; case 2 : return times3 ; default : return finc ; } ; } //------------------------------------------- Int2Int* pick(int n) { static AddX add3(3) ; // really should be const static AddX add5(5) ; static Mult3 times3 ; static IncX finc ; switch (n) { case 0 : return &add3 ; case 1 : return &add5 ; case 2 : return ×3 ; default : return &finc ; } ; } //------------------------------------------- int main () { int B[10] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19} ; printf("Before:\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } Int2Int& plus3 = select(0) ; apply (plus3, B, 10) ; printf("\n\nAfter calling apply(plus3, B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } Int2Int& plus5 = select(1) ; apply (plus5, B, 10) ; printf("\n\nAfter calling apply(plus5, B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } apply (select(2), B, 10) ; printf("\n\nAfter calling apply(select(2), B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } Int2Int *fptr ; fptr = pick(0) ; // add3 apply (*fptr, B, 10) ; printf("\n\nAfter calling apply(*fptr, B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } fptr = pick(1) ; // add5 apply (*fptr, B, 10) ; printf("\n\nAfter calling apply(*fptr, B, 10):\n") ; for (int i=0 ; i < 10 ; i++) { cout << " B[" << i << "] = " << B[i] << endl ; } }