반응형
함수 포인터 (Function Pointer)
기본 예제
배열에서 짝수, 홀수를 각각 출력하는 예제
-
간단한 버전
#include <iostream> #include <array> using namespace std; void printNumbers(const array<int, 10>& arr, \ bool print_even) { for (auto e : arr) if ((print_even && e % 2 == 0) || \ (!print_even && e % 2 == 1)) cout << e; cout << endl; } int main() { array<int, 10> arr{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; printNumbers(arr, true); printNumbers(arr, false); } /* stdout stderr 02468 13579 */ -
함수를 나누고 함수 포인터로 전달
#include <iostream> #include <array> using namespace std; bool isEven(const int& number) { if (number % 2 == 0) return true; else return false; } bool isOdd(const int& number) { if (number % 2 == 1) return true; else return false; } void printNumbers(const array<int, 10>& arr, \ bool (*check_fcn)(const int&) = isEven) { for (auto e : arr) if (check_fcn(e)) cout << e; cout << endl; } int main() { array<int, 10> arr{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; printNumbers(arr); printNumbers(arr, isOdd); } /* stdout stderr 02468 13579 */ -
typedef로 정리#include <iostream> #include <array> using namespace std; bool isEven(const int& number) { if (number % 2 == 0) return true; else return false; } bool isOdd(const int& number) { if (number % 2 == 1) return true; else return false; } typedef bool (*check_fcn_t)(const int&); //using check_fcn_t = bool (*)(const int&); void printNumbers(const array<int, 10>& arr, \ check_fcn_t check_fcn = isEven) { for (auto e : arr) if (check_fcn(e)) cout << e; cout << endl; } int main() { array<int, 10> arr{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; printNumbers(arr); printNumbers(arr, isOdd); } /* stdout stderr 02468 13579 */ -
C++11의
<functional>라이브러리 사용#include <iostream> #include <array> #include <functional> using namespace std; bool isEven(const int& number) { if (number % 2 == 0) return true; else return false; } bool isOdd(const int& number) { if (number % 2 == 1) return true; else return false; } void printNumbers(const array<int, 10>& arr, \ std::function<bool(const int&)> check_fcn) { for (auto e : arr) if (check_fcn(e)) cout << e; cout << endl; } int main() { array<int, 10> arr{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; std::function<bool(const int&)> fcnptr = isEven; printNumbers(arr, fcnptr); fcnptr = isOdd; printNumbers(arr, fcnptr); } /* stdout stderr 02468 13579 */
반응형
'SW개발 > C++' 카테고리의 다른 글
| C++ assert (0) | 2021.03.12 |
|---|---|
| C++ vector (0) | 2021.03.12 |
| C++ 인라인 함수 (Inline Function) (0) | 2021.03.12 |
| C++ tuple (0) | 2021.03.12 |
| 따라하며 배우는 C++ 7장 (0) | 2021.03.12 |