PDA

View Full Version : pass member function as argument int template function



bibhukalyana
12th March 2013, 04:59
Hi everyone

I am trying to pass a member function as an argument to another template member funtion.
But during build time i am getting an error -: error: no matching function for call to 'A::do_op(int&, int&, <unresolved overloaded function type>)'

My .h file is :



class A
{
public:
A();

int test_op(int x,int y);

private:
int add(int x, int y);
int sub(int x, int y);

template<class F>
int do_op(int x, int y, F &fun)
{
return fun(x,y);
}

};


cpp file :




template<class F>
int do_op_global(int x, int y, F &fun)
{
return fun(x,y);
}
int add_global(int x, int y)
{
return (x+y);
}


A::A()
{}

int A::add(int x, int y)
{
return (x+y);
}

int A::sub(int x, int y)
{
return (x-y);
}

int A::test_op(int x, int y)
{
int m = do_op_global(x,y,add_global); // Statement 1
int n = do_op(x,y,sub); // Statement 2

return (m+n);
}


Only statement 2 is giving error.

Is there any restriction for template function inside class ?
Please help me how i will pass a member function as argument.

thanks.

lanz
12th March 2013, 07:05
Use std::mem_fun (http://www.cplusplus.com/reference/functional/mem_fun/) it wraps member function inside function object.