Reputation: 583
I am writing a program for an assignment for a post fix calculator. There are bonus points if I can do it without using an if statement (no switch or while or any comparisons). I was reading about function pointers and came up with the following code:
int main(){
unordered_map<char,int*(int,int)> m;
m.insert({'+',[](int const a, int const b){return a+b;}});
}
This doesn't work.
However this does:
int main(){
unordered_map<char,int(*)(int,int)> m;
m.insert({'+',[](int const a, int const b){return a+b;}});
}
Why are (*)
and *
different?
Upvotes: 2
Views: 177
Reputation: 56557
The type of
int* (int,int)
is function taking (int, int)
and returning int*
, i.e. a pointer to int
. On the other hand, the type of
int (*) (int, int)
is pointer to function taking (int, int)
and returning int
. So they are different declarations. In your map you insert types that are decay-able to the latter, not the former, and that's why the latter code works but not the former.
Useful: http://www.cdecl.org/
Super useful: The clockwise/Spiral rule
Upvotes: 5
Reputation: 490148
Without the parens, the int*
is parsed as just "pointer to int", and the rest of the code just doesn't work.
With the parens, int (*)
means "pointer to function returning an int" instead, and the parens (and stuff they enclose) specify the arguments to that function, so it all parses as what you want.
Upvotes: 3