Passing a member function as a parameter of a member function

A

Azdo

Hi,

is it possible to pass a member function pointer to other member
function of the same class in order to get different behaviours?
Something like

class A
{

int m(int d) /* First way */
{
return d;
}

int n(int d) /*Second way*/
{
return d+2;
}

/* This does the calculations depending on the function passed */

void f(int (*g)(int))
{
std::cout << g(8) << "\n";
}

void start()
{
f(&m); /* Do it the "m" way */
f(&n); /* Do it the "n" way */
}
};

What I am trying to accomplish is to have a member function that can
call different procedures to do slightly different jobs.

Thank you,
 
M

Michael DOUBEZ

Azdo a écrit :
Hi,

is it possible to pass a member function pointer to other member
function of the same class in order to get different behaviours?
Something like

class A
{
int m(int d) /* First way */
[snip]
int n(int d) /*Second way*/
[snip]

/* This does the calculations depending on the function passed */

void f(int (*g)(int)
[snip]
void start()
{
f(&m); /* Do it the "m" way */
f(&n); /* Do it the "n" way */
}
};

What I am trying to accomplish is to have a member function that can
call different procedures to do slightly different jobs.

The declation of f() would take a pointer on A's member function:
void f(int (A::*g)(int));
{
std::cout << this->*g(8) << "\n";
}

and
f(&A::m);
f(&A::n);


Michael
 
A

Azdo

Azdo a écrit :


is it possible to pass a member function pointer to other member
function of the same class in order to get different behaviours?
Something like
class A
{
int m(int d) /* First way */
[snip]
int n(int d) /*Second way*/
[snip]
/* This does the calculations depending on the function passed */
void f(int (*g)(int)
[snip]
void start()
{
f(&m); /* Do it the "m" way */
f(&n); /* Do it the "n" way */
}
};
What I am trying to accomplish is to have a member function that can
call different procedures to do slightly different jobs.

The declation of f() would take a pointer on A's member function:
void f(int (A::*g)(int));
{
std::cout << this->*g(8) << "\n";

}

and
f(&A::m);
f(&A::n);

Michael

Great! I had however to do a tiny change for that to work:

std::cout << (this->*g)(8) << "\n";

Thank you very much Michael.
 

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

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top