The question may be a bit confusing, but the concept is relatively simple.
I have a function that is passed any given non-static class method and object pointer, and binds these to yield a simple function pointer (see code below),
I have a particular signature (return type void, one argument of type int), that I wish the method to be:
header file:
//method_pointer.hpp
#include <boost/bind.hpp>
#include <boost/function.hpp>
class A
{
public:
void aMethod( int );
};
class B
{
public:
template < class T >
B( boost::function< void ( int ) > method_ptr,
T * obj_ptr )
{
bCallAMethod( boost::bind( method_ptr, obj_ptr, _1 ) );
}
void bCallAMethod( boost::function< void (int ) > );
};
source file:
// method_pointer.cpp
#include <cstdio>
#include "method_pointer.hpp"
void A::aMethod( int x )
{
printf("My number: %d\n", x);
}
void B::bCallAMethod( boost::function<void ( int ) > method_ptr )
{
method_ptr( 5 );
}
int main( void )
{
A a;
B b( &A::aMethod, &a );
return 1;
}
The main code instantiates an object of class A; then instantiates an object of class B by passing a method and instance of A to the constructor. B should then be able to call the method in A by this boost::function.
I know how to do this if I know which method is being passed in (eg &A::aMethod), but the goal is to generalize to any method with that signature.
I am getting the compilation error
$ g++ method_pointer.cpp -lboost_system -lrt
method_pointer.cpp: In function ‘int main()’:
method_pointer.cpp:18:11: error: invalid use of non-static member function ‘void A::aMethod(int)’
Any ideas?
I'm also open to being consistent and using some boost function for the class template if possible.
You need to change B
constructor's prototype to :
template<typename T>
B (void (T::*method_ptr)(int), T * obj_ptr)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.