Design Question - Templates

Consider the following declaration

1
2
3
4
5
6
7
8
9
10
11
typedef void(*PEHF)();

   class X 
   {
     private:
          static PEHF currentPEHF;
     public:
          static PEHF set_new_handler(PEHF);
          void * operator new(size_t size);
          //.... other class specific functions
   };


Now, assume that the implementation of the functions above apart from //.... other class specific functions are same and there is absolutely no change. So how can we use templates to write one implemention for all the classes?
You can't*. This sounds more like a job for inheritance.



* Well, at least not AFAIK.
Last edited on
AFAIK, you do need inheritance to accomplish the above, but simply deriving from a base class that implements this functionality won't work as the data member and function are static. Try:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
typedef void(*PEHF)();

template <class T>
class Base
{
 private:
	  static PEHF currentPEHF;
 public:
	  static PEHF set_new_handler(PEHF p){ currentPEHF = p; return currentPEHF;}
};

template <class T> PEHF Base<T>::currentPEHF;

class A : public Base<A>
{
public:
	  //.... other class specific functions
};


(hoping this isn't a homework assignment :P)

-Rollie
Something like this could also be of help:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <cstdio>
using namespace std;

struct ImplC
{
    void Print(int n)
    {
        printf("(using C implementation) %d\n",n);
    }
};

struct ImplCPP
{
    void Print(int n)
    {
        cout << "(using C++ implementation) " << n << endl;
    }
};

template <class Implementation>
class MyClass: public Implementation
{
public:
    int data;

    void Print()
    {
        Implementation::Print(data);
    }
};

int main()
{
    MyClass<ImplC> my_C_object;
    MyClass<ImplCPP> my_CPP_object;

    my_C_object.data=10;
    my_CPP_object.data=25;

    my_C_object.Print();
    my_CPP_object.Print();

    cout << "\nhit enter to quit...";
    cin.get();
};
Topic archived. No new replies allowed.