I am trying to understand how to use functional pointers to map the method from instances in C++ like delegates in C#.
class FunctionalPointers
{
public:
static int IncrementCounter ( int *a, int b )
{
return *a += b;
}
int NonStaticIncrementCounter ( int *a, int b )
{
return *a += b;
}
};
//Declare a functional pointer as a separate type.
typedef int ( *AFunctionalPointer ) ( int*, int );
int _tmain(int argc, _TCHAR* argv[])
{
int a = 10;
int *ptr = &a;
*ptr = 200;
//This works as the methods are static
AFunctionalPointer funcInstance = FunctionalPointers::IncrementCounter;
int result = funcInstance( ptr, a );
//But if I try to make the same call from an
//instance of a non static method I get an error. Why ?
FunctionalPointers *functionalPointer = new FunctionalPointers();
//ERROR : Compiler says it's illegal operation.
AFunctionalPointer funcClassInstanceType = *functionalPointer->IncrementCounter;
int instanceResult = funcClassInstanceType( ptr, a );
return 0;
}
As you can see above, if a static method is assigned to the functional pointer it compiles perfectly but if I try to do the same thing with non static method with the instance of the class, the compiler throws an illegal operation error.
Mapping an instance method to a delegate in C# is very much possible like the snippet below
class Program
{
static void Main( string[] args )
{
int a = 200;
int b = a;
FunctionalPointer funcInstance = new FunctionalPointer();
AFunctionalPointer degegateInstance = funcInstance.Increment;
int result = degegateInstance( 200, 200 );
}
}
public delegate int AFunctionalPointer( int a, int b );
class FunctionalPointer
{
public int Increment ( int a, int b )
{
return a += b;
}
public int Decrement( int a, int b )
{
return a -= b;
}
}
My question is,
Is it a knowledge gap on my part or is it a part of the rule in C++ to define function pointers in a different way to support instance types.
C++ requires different pointer types for member functions. The C++ FAQ has a whole section on them.
You can get C#-like behavior by using the std::function wrapper from C++11.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With