Template parameter to member function problem

O

Oplec

Hi, I have a class template that takes an argument to a class and an
argument to a member function of the given class. I have to use
template<class T, void (T::*MF)()> but would like to use something along
the lines of template<class T, class MF>. Is that possible? Below is the
code of my currently working method.

#include <cstdlib>
#include <iostream>

template<class C, void (C::*MF)()>
class A {
public:
A(C& o) : object_(o) { }
void operator()() { (object_.*MF)(); }

private:
C& object_;
};

struct B {
void f() { std::cout << "B::f()\n"; }
};

int main()
{
B b;
A<B,&B::f> aa(b);

// output: B::f()
aa();

system("PAUSE");
}
 
V

Victor Bazarov

Oplec said:
Hi, I have a class template that takes an argument to a class and an
argument to a member function of the given class. I have to use
template<class T, void (T::*MF)()> but would like to use something along
the lines of template<class T, class MF>. Is that possible?

Of course it's possible. Have you tried?

The difference is that 'void (T::*MF)()' is a non-type parameter.
You want a _type_ parameter (who knows why?). Since you're going to
remove the way to pass the actual pointer, you have to change the
interface of the class A so that the pointer is passed elsewhere.
Below is the
code of my currently working method.

#include <cstdlib>
#include <iostream>

template<class C, void (C::*MF)()>
class A {
public:
A(C& o) : object_(o) { }
void operator()() { (object_.*MF)(); }

private:
C& object_;
};

struct B {
void f() { std::cout << "B::f()\n"; }
};

int main()
{
B b;
A<B,&B::f> aa(b);

// output: B::f()
aa();

system("PAUSE");
}

Before we can tell you the solution, you have to tell us
the problem. A<B,&B::f> is the current way to pass the
pointer to a member of B. How would you like to pass it
instead? You could do

A<B> aa(b, &B::f);

is that what you need? You could also do

aa(&B::f);

is that what you need? Don't keep us guessing.

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top