C++/따배C++ 19강 모던 C++ 기능들
[C++/CPP] 19.01 모던 C++ lambda function, std::function, std::bind, std::placeholders
polarcompass
2021. 12. 11. 06:26
728x90
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<functional>
void goodbye(const std::string& s)
{
std::cout << "Goodbye " << s << std::endl;
}
class Object
{
public:
void hello(const std::string& s)
{
std::cout << "Hello " << s << std::endl;
}
};
int main(int argc, char const *argv[])
{
// lambda-introducer
// lambda-parameter-declaration
// lambda-return-type-clause
// compound-statement
using namespace std;
auto func = [](const int& i) -> void {cout << "Hello, World!" << endl;};
func(123);
[](const int& i) -> void { cout << "Hello, World!" << endl;}(1234);
{
// [&] : name을 참조해서 가져올 수 있음.
string name = "JackJack";
[&](){cout << name << endl;}();
// [=] : name을 복사해서 가져올 수 있음.
name = "sudo";
[=](){cout << name << endl;}();
}
vector<int> v;
v.push_back(1);
v.push_back(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 << []() -> auto { return 10;}() << endl;
// function pointer
std::function<void(int)> func3 = func2;
func3(123);
std::function<void(void)> func4 = std::bind(func3, 456);
func4();
{
Object instance;
// bind( 클래스 멤버 함수 포인터, 클래스 인스턴스 포인터, 파라미터 개수 지정(1~10))
auto f = std::bind(&Object::hello, &instance, std::placeholders::_1);
f(string("World"));
// bind( 함수 포인터, 파라미터 개수 지정)
auto f2 = std::bind(&goodbye, std::placeholders::_1);
f2(string("World"));
}
return 0;
}
출력 결과
Hello, World!
Hello, World!
JackJack
sudo
1
2
1
2
10
123
456
Hello World
Goodbye World
728x90