Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointer to member function of an UNKNOWN CLASS

DISCLAIMER I DO NOT USE BOOST OR OTHER LIBRARIES

Finally I've learned how PointerToMemberFunction works. This is my example code.

#include <iostream>

using namespace std;

class Foo
{
        public:
                void foo ( )
                {
                        cout << "I'm a foo method\n";
                };
};

class Bar
{
        public:
                void bar ( Foo* fooPtr , void(Foo::*fooFnPtr)() )
                {
                        (fooPtr->*fooFnPtr)();
                };
};

int main()
{
        Foo* foo = new Foo();
        Bar* bar = new Bar();

        bar->bar ( foo , &Foo::foo );

        return 0;
}

Now, what the problem is. Bar::bar must be modified somehow, because in real project it won't know, what class fooFnPtr is a pointer to. In other words Bar::bar must work with any class, not only with Foo. I won't know, a pointer to an instance of what class is passed to Bar::bar.

The one thing which can help is that all classes which will work with Bar::bar are children of one class!

Is this achievable and how? How do i fix my code? Thanks in advance!

like image 905
Kolyunya Avatar asked Jan 23 '26 05:01

Kolyunya


1 Answers

You could make bar a template function:

template<class T>
void bar ( T* fooPtr , void(T::*fooFnPtr)() )
{
    (fooPtr->*fooFnPtr)();
}

Of course, if you only want to pass pointers to members that exist in the common base class, you can simply do this:

#include <iostream>

using namespace std;

class Foo
{
        public:
                virtual void foo ( )
                {
                        cout << "I'm a foo method\n";
                };
};

class Derived: public Foo
{
        public:
                virtual void foo ( )
                {
                        cout << "I'm a Derived method\n";
                };
};


class Bar
{
        public:
                void bar ( Foo* fooPtr , void(Foo::*fooFnPtr)() )
                {
                        (fooPtr->*fooFnPtr)();
                }
};

int main()
{
        Derived* derived = new Derived();
        Bar* bar = new Bar();

        bar->bar ( derived , &Foo::foo );

        return 0;
}
like image 62
Henrik Avatar answered Jan 24 '26 21:01

Henrik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!