I was wondering if is possible to point a function of other structure into of a structure:
Example:
typedef struct
{
int func(int z)
{
return z * 2;
}
} sta;
typedef struct
{
int(*this.func)(int);
} stah;
int main()
{
sta sa;
stah sah;
sah.func = &sa.func;
return 0;
}
it's possible this in a struct?
After trying and trying, the solution it was something like this:
Example:
Finding memory address
then the code compiles without warnings, the objective is hook the structure with their functions.
The declaration of
func
should look like this:Or, alternatively:
This is easier to read:
my_type
is an alias for the type pointer to a member function ofsta
that gets anint
and returns anint
.func
is nothing more that a data member having typemy_type
.In order to assign an actual pointer to member function to
func
, you can do this instead:You can then invoke it as it follows:
The correct syntax for a pointer to method is:
Where
T
is a type declaring a methodf
. Note that to be called, the pointer must be bound to an instance ofT
, because the value of the pointer represents an offset to the beginning of an instance in memory.In C++14, you may consider
std::function
:You can also use lambdas instead of
std::bind
:See
std::function
,std::bind
, andstd::placeholders
on cppreference.com.