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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With