If I have two classes like this :
class A
{
public:
int *(*fun)( const int &t );
A( int *( *f )( const int &t ) ) : fun( f ) {}
};
class B
{
private:
float r;
int *f(const int &t)
{
return new int( int( r ) + t );
}
A a;
B() : a( A( f ) ) {}
};
This results in compiler error.
I want to assign f
to a
's function pointer.
The thing is that A
can be used by many classes not just B
so I can't simply define fun
as B::*fun
.
None of the posts I've found on the internet and here on stackoverflow address the issue of using the function pointers with many classes each having its own member function but the same prototype.
So what to do?
Because
f
is aA
's non-static member function returningint*
, that accepts single const reference toint
. That means, that its type is not:but:
Also, your code signalizes very bad design - I think you need simple virtual function. But if you want to keep writing things this way, you may want to read: ISOCPP: Pointers to members.
Remember, that non-static member functions of type
C
always accepts additional implicit argument of typeC*
(orconst C*
, if function is declared withconst
qualifier), that points to instance ofC
this function was called on.Your code looks confusing and, personally, I believe that C function pointers look ugly on C++'s OO implementation. So I would advise you to use the
std::function
. It only has been available sinceC++11
. If you cannot use it, try looking on Boost's Implementation.I can give you an example of how to use the
std::function
:Using this you will drastically improve your code reliability. As of your problem, specifically:
You have to add the following namespace:
Not much. Other than templating
A
on the type of objects for which it will hold a pointer to a member function taking a reference to a const int and returning a pointer to int.What you're trying to do is to mix a pointer to a free function with a pointer to member function. Whilst it sounds like they're both function pointers they're different enough to not be able to pass through the same type definition.