문제

I am trying to pass a function from a class to other function argument. I get this error.

error: the argument of type ‘void (A_t::)(int)’ doesn't match with ‘void (*)(int)’

Is there a way to manage this, still using the function inside the class a. Thanks in advance.

#include <iostream>

using namespace std;

void procces(void func(int x),int y);

class A_t
{
   public:
      A_t();
      void function(int x)
      {
          cout << x << endl;
      }
};

int main()
{
   A_t a;

   procces(a.function,10);
}

void procces(void func(int x),int y)
{
    func(y);
    return;
}
도움이 되었습니까?

해결책

Here is an example of how you can use a pointer-to-function-member :

class A_t {
public:
    void func(int);
    void func2(int);
    void func3(int);
    void func4(int);
    ...
};

typedef  void (A_t::*fnPtr)(int);


int process(A_t& o, fnPtr p, int x)
{
    return ((o).*(p))(x);
}

int main()
{
    fnPtr p = &A_t::func;
    A_t a;
    process( a, p, 1 );
    ...
}

In the main function you can use the func member function as well as func2, func3 or func4.

다른 팁

function() must be declared as static in order for this to work. If you're putting a non-static member function in a class, it's tied to the specific instance of the class.

and if you want define an API for which you can map C function and C++ member function, define process as below, and use a binding to pass member function ....

NB: not tested (I'm on my mobile!)

 class A {
 public:
     void func(int);
     static void StaticWrapper(A* ptr, int i)
     { ptr->func(i);}
...
};

 typedef  void (CStyleCB*)(int);


  int process( CStyleCB p, int x)
  {
      return (*p)(x);
  }

  int main()
  {
      A a;
      process( bind(&A::StaticWrapper, this, _1),   1 );
       ...
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top