Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling different methods with the same signature using a template like mechanism

I have this code:

struct C
{
   int d1;
   int d2;
};

struct A
{
      void  write(C data)
      {
      }
};

struct B
{
      void use(C data)
      {
      }
};

Now I want to define a new class that uses A or B and call their write and use method. Something such as this:

template <class T>
struct D
{
     T t;
     D(T myT) { t=myT; }
     void myFunct(C data)
     {
         // t.????(data);
     }
};

As you can see if the two classes had similar method names, then it would be easy to implement D, but since A and B have different methods, then I need to tell compiler which method it should use. How can I do this?

I don't want to change A or B and also I don't want to create a subclass of A and B to create a method with the same name.

I want a way to tell the compiler which method to use as part of the template, is it possible?

like image 411
mans Avatar asked Nov 30 '22 08:11

mans


1 Answers

You can pass a pointer to member-function as a second template parameter to D:

template <class T, void (T::*fun)(C)>
struct D
{
    T t;

    void myFunct(C data)
    {
        (t.*fun)(data);
    }
};

You can then create D objects doing:

D<A, &A::write> da;
D<B, &B::use> db;
like image 98
Holt Avatar answered Dec 05 '22 15:12

Holt