람다함수와 std::function
사용법
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
void goodbye(const string& s)
{
cout << "Good bye" << s << endl;
}
class Object
{
public:
void hello(const string& s)
{
cout << "Hello" << s << endl;
}
};
int main()
{
//유연한 프로그래밍을 할때 사용
//gui프로그래밍시 주로 사용
//lambda - introducer
//lambda - parameter - declaration
//lambda - return - type - clause
//compound - statement
auto func = [](const int& i) -> void {cout << "Hello" << endl; };
func(123);
//익명일때도 실행이 됨
[](const int& i) -> void {cout << "Hello" << endl; }(456);
{
string name = "JACKJACK";
//[&]밖에있는걸 레퍼런스로 가져옴
//[=]copy
[&]() {cout << name << endl; }();
}
vector<int>v = {1, 2};
auto func2 = [](int val) {cout << val << endl; };
for_each(v.begin(), v.end(), func2);
//for_each(v.begin(), v.end(), [](int val) {cout << val << endl; });
cout << []() -> int {return 1; }() << endl;
//function pointer를 체계화
std::function<void(int)> func3 = func2;
func3(123);
//묶어줌? 파라미터와 묶어줌.
std::function<void()>func4 = bind(func3, 456);
func4();
//placeholder
{
Object instance;
auto f = bind(&Object::hello, &instance, placeholders::_1);
f(string("World"));
auto f2 = bind(&goodbye, placeholders::_1);
f2(string("World"));
}
return 0;
}
후기
이건 배우면서도 뭔소리가 싶은 파트였다.
하지만 익숙해지기만 한다면, 코딩량을 줄이는데도 유용할거 같긴하다.