Created
November 23, 2024 13:16
-
-
Save farhangamary/0eea2f3c0c6c0f87d060b941a9f8905e to your computer and use it in GitHub Desktop.
Interesting kind of declarations for function pointers for example: int (*(*a[])(int))(string)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <string> | |
| #include <algorithm> | |
| using namespace std; | |
| typedef int (*custom_ln)(string); | |
| typedef custom_ln (*ln_mapper)(int); | |
| int cnt_0(string str) | |
| { | |
| return count_if(str.begin(), str.end(), [](char ch) | |
| { return ch == '0'; }); | |
| } | |
| int cnt_a(string str) | |
| { | |
| return count_if(str.begin(), str.end(), [](char ch) | |
| { return ch == 'a'; }); | |
| } | |
| custom_ln fn_mapper(int idx) | |
| { | |
| return idx == 0 ? cnt_0 : idx == 1 ? cnt_a | |
| : nullptr; | |
| } | |
| int main() | |
| { | |
| ln_mapper mappers[] = {fn_mapper}; | |
| cout << "calling mappers[0](1)(\"My name is Farhang.\"):\t" | |
| << mappers[0](1)("My name is Farhang.") << endl; | |
| cout << "calling: mappers[0](1)(\"The year 2024!\"):\t" | |
| << mappers[0](1)("The year 2024!") << endl; | |
| // A similar way but no use of typedef | |
| int (*(*mappers2[])(int))(string) = {fn_mapper}; | |
| cout << "calling mappers2[0](1)(\"My name is Farhang.\"):\t" | |
| << mappers2[0](1)("My name is Farhang.") << endl; | |
| cout << "calling: mappers2[0](1)(\"The year 2024!\"):\t" | |
| << mappers2[0](1)("The year 2024!") << endl; | |
| return EXIT_SUCCESS; | |
| } | |
| /* | |
| -> g++ -o out funptr.cpp | |
| -> ./out | |
| calling mappers[0](1)("My name is Farhang."): 3 | |
| calling: mappers[0](1)("The year 2024!"): 1 | |
| calling mappers2[0](1)("My name is Farhang."): 3 | |
| calling: mappers2[0](1)("The year 2024!"): 1 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment