
c++ 11 std::function
DevCho1107
·2023. 5. 23. 00:54
c에서 있는 함수포인터랑 비슷하다.
C++ 11에 표준에 포함되었고, 기본 문법은 다음과 같다.
std::function<return_type(argument_types)>
기초적인 예제는 아래와 같다.
#include <iostream>
#include <functional>
void repeatFunction(std::function<void(int, int)> func, int a, int b, int count) {
for (int i = 0; i < count; ++i) {
func(a, b);
}
}
void printSum(int a, int b) {
std::cout << "Sum: " << a + b << std::endl;
}
void printProduct(int a, int b) {
std::cout << "Product: " << a * b << std::endl;
}
int main() {
repeatFunction(printSum, 2, 3, 5);
repeatFunction(printProduct, 2, 3, 3);
return 0;
}
근데, 보통 function 쓰는 부분 보면 이렇게 아래와같이 쓰는걸 많이 봤다.
#include <iostream>
#include <functional>
void repeatFunction(std::function<void(int, int)> func, int a, int b, int count) {
for (int i = 0; i < count; ++i) {
func(a, b);
}
}
int main() {
int sumCount = 5;
int productCount = 3;
// function과 람다를 같이 쓰는..
repeatFunction(
[](int a, int b) {
std::cout << "Sum: " << a + b << std::endl;
},
2, 3, sumCount
);
repeatFunction(
[](int a, int b) {
std::cout << "Product: " << a * b << std::endl;
},
2, 3, productCount
);
return 0;
}
그리고 14 부터 auto 키워드에 함수타입 추론이 가능해진걸로 아는데, 아래와 같이 사용할 수 있다.
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> numbers = { 5, 2, 7, 1, 8 };
auto sortFunc = [&](auto a, auto b) {
std::sort(a, b);
};
sortFunc(numbers.begin(), numbers.end());
for (const auto& number : numbers) {
std::cout << number << " ";
}
std::cout << std::endl;
return 0;
}
이거 auto 에 마우스 올려보면 lambda 라고 나오는데, 암시적형변환을 통해 std::function 으로 변환된다.
'< Programming > > C++' 카테고리의 다른 글
std::next와 std::advance의 차이점 (0) | 2023.06.08 |
---|---|
c++ Lambda (0) | 2023.05.23 |
emplace_back (0) | 2023.05.08 |
constexpr ( generalized constant expressions ) (0) | 2023.05.04 |
C++ 17 에서 업데이트 된 기능 정리. (0) | 2023.04.25 |