7.9 함수포인터
#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;
}
// typedef bool (*check_fcn_t)(const int&);
using check_fcn_t = bool(*)(const int&);
void printNumbers(const array<int, 10> &my_array,
std::function<bool(const int&)> fcnptr){
for (auto element: my_array){
if (fcnptr(element)) cout << element << " ";
}
cout << "\n";
}
int main(){
std::array<int,10> my_array{0,1,2,3,4,5,6,7,8,9};
std::function<bool(const int&)> fcnptr = isEven;
printNumbers(my_array, fcnptr);
fcnptr = isOdd;
printNumbers(my_array, fcnptr);
return 0;
}
함수도 포인터처럼 사용이 가능한데, typedef bool (check_fcn_t)(const int&) 이나 using check_fcn_t = bool()(const int&) 처럼 자료형으로 쓸 수가 있고, std::function<>을 이용해서 포인터처럼 사용이 가능하다. fcnptr()과 같이 쓰면 함수를 불러오는 것이 되므로 함수 이름만 쓴다.