When I first started using C ++, I always forgot the syntax of defining pointers to functions, and especially pointers to function members.
Later I found out about a small lifehack that helped me get rid of the syntax for defining pointers to functions. The truth is that this all somehow somehow settled in my head a little later and it even became obvious.
The other day I showed this lifehack to one programmer and decided to share it here.
To avoid long explanations, I will give an example:
struct test
{
virtual int foo (const test &) const
{
return 0;
};
virtual ~ test ()
{}
};
Suppose further on the code we need to declare a pointer to test :: foo.
In order to find out how it should be declared, we will write the following:
char c = &test::foo;
and try to build it (for example, I’ll use the Microsoft compiler, although I’ve tested it on gcc and Comeau Online Compiller).
')
We get the following error:
error C2440: 'initializing': cannot convert from 'int (__thiscall test :: *) (const test &) const' to 'char'
From this error we will take the syntax of declaring a pointer to this member (we explicitly indicate the type of the __thiscall call):
int ( test::* )(const test &) const
Now add the variable and initialization:
int ( test::* func )(const test &) const = &test::foo;
Done!