Let’s say that I have the function
doSomething(char* (*getterOne)())
{
//do something here
}
although I’ve named the parameter of doSomething "getterOne", I have no way of verifying that the function is going to be a getter ( I think? ). So I wonder, is there a way to explicitly specify the kind of function that can be passed as an argument? For example, if I have the class "Cat", is there a way to say that the function doSomething accepts as parameter function, that belongs to the class Cat, and if so, how can I use it like this:
doSomething(char* (*getterOne)())
{
Cat cat;
cat.getterOne(); // where getterOne will be the getter that I pass as a parameter and do something with it
}
Also if anyone asks why I use char* instead of string, it is for a school project and we are not allowed to use string.
>Solution :
A function pointer and a pointer-to-member-function are two different things. If you make a function that accepts a pointer-to-member-function you have no choice but to specify which class it belongs to.
Here is an example.
#include <iostream>
struct Cat {
char* myGetter() {
std::cout << "myGetter\n";
return nullptr;
}
};
void doSomething(char* (Cat::*getterOne)())
{
Cat cat;
(cat.*getterOne)();
}
int main() {
doSomething(&Cat::myGetter);
}
The syntax for using a pointer-to-member is .*
or ->*
and the extra brackets are needed.