I have functions Mult, Add, Div, Sub, Mod
those takes two integers and returns the result of its parameters. And a function Calc
that takes a character as an Operator
and returns a pointer to function that returns an integer and takes two integer parameters like Mult
.
- Functions like
Mult
's second parameter isdefault
So when I callCalc
,Calc
returns the address ofMult
orAdd
... depending on the value of parameter ofCalc
thus I can pass only one argument.
But It doesn't work with pointer to function:
int Add(int x, int y = 2) { // y is default
return x + y;
}
int Mult(int x, int y = 2) { // y is default
return x * y;
}
int Div(int x, int y = 2) { // y is default
return y ? x / y : -1;
}
int Sub(int x, int y = 2) { // y is default
return x - y;
}
int Mod(int x, int y = 2) { // y is default
return y ? x % y : -1;
}
using pFn = int(*)(int, int);
pFn Calc(char c) {
switch (c) {
case '+':
return Add;
case '*':
return Mult;
case '/':
return Div;
case '-':
return Sub;
case '%':
return Mod;
}
return Mult;
}
int main(int argc, char* argv[]){
pFn func = Calc('%');
cout << func(7, 4) << endl; // ok
//cout << func(7) << endl; // error: Too few arguments
cout << Mult(4) << endl; // ok. the second argument is default
func = Calc('/'); // ok
cout << func(75, 12) << endl; // ok
std::cout << std::endl;
}
Above if I call Mult
with a single argument it works fine because the second argument is default but calling it through the pointer func
it fails. func is pointer to function that takes two integers and returns an int.