How to pass a method of derived class as parameter to another method in base class

Hey friends,

I have a question similar to the one here: http://www.cplusplus.com/forum/general/39769/

The main difference is I would like to pass a method of derived class as a parameter to some other method in its template base class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
template <typename BaseType>
class Base
{
    public:

        typedef void (Base::*Callback)(int A);

        void BaseMethod(Callback *method)
        {
            DerivedCallback();
        }
};

class Derived : public Base<int>
{
    public:

        void DerivedCallback1(int A)
        {
            /* do stuff */
        }

        void DerivedCallback2(int A)
        {
            /* do stuff */
        }

        void DerivedMethod()
        {
            BaseMethod(DerivedCallback1);
            BaseMethod(DerivedCallback2);
        }
};

int main()
{
    Derived d;

    return 0;
}


The above is an example which does not compile. My compiler complains that the two BaseMethod() calls in DerivedMethod() are invalid uses of non-static member function.

Is this not possible to do, or is my syntax simply wrong? All I want is to be able to pass as an an argument to a method in the base class from the derived class some callback as a variable for the base class to invoke later.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <functional>

template < typename T > struct base
{
    // http://en.cppreference.com/w/cpp/utility/functional/function
    void call_it( std::function< void(int) > fn )
    {
        std::cout << "base::call_it => " ;
        fn(100) ;
    }
};

struct derived : base<int>
{
    void foo( int ) { std::cout << "derived::foo\n" ; }
    void bar( int ) { std::cout << "derived::bar\n" ; }

    // http://en.cppreference.com/w/cpp/utility/functional/bind
    void call_foo() { call_it( std::bind( &derived::foo, this, std::placeholders::_1 ) ) ; }
    void call_bar() { call_it( std::bind( &derived::bar, this, std::placeholders::_1 ) ) ; }
};


int main()
{
    derived d ;
    d.call_foo() ;
    d.call_bar() ;
    d.call_it( []( int ) { std::cout << "call this\n"; } ) ;
}

http://coliru.stacked-crooked.com/a/fd78c07c53b69895
Thank you JLBorges. That is a much better solution than the one I was trying. This way one can use lambda closures.
Topic archived. No new replies allowed.