jeudi 21 juillet 2016

Avoid the class scope so as to pass a member function as a function pointer ( C++)

I'll describe my question using the following sample code.

I have class B defined as follows:

class B
{
    public:
        inline B(){}
        inline B(int(*f)(int)) :myfunc{ f }{}
        void setfunction(int (*f)(int x)) { myfunc = f; }
        void print(int number) { std::cout << myfunc(number) << std::endl; }
    private:
        int(*myfunc)(int);
};

I then define class A as follows:

class A
{
    public:
    A(int myint) :a{ myint }{ b.setfunction(g); }
    int g(int) { return a; }
    void print() { b.print(a); }

   private:
   B b;
   int a;
   };

To me the issue seems to be that the member function g has the signature int A::g(int) rather than int g(int).

Is there a standard way to make the above work? I guess this is quite a general setup, in that we have a class (class B) that contains some sort of member functions that perform some operations, and we have a class (class A) that needs to use a particular member function of class B -- so is it that my design is wrong, and if so whats the best way to express this idea?

Aucun commentaire:

Enregistrer un commentaire