👉🏻 다음코드처럼 람다함수란 이름없는 익명함수를 의미합니다.
As shown in the following code, a lambda function refers to an unnamed anonymous function.
[&](const std::string& req) -> std::string {
return router(req);
}
👉🏻 위와 같은 람다함수를 파라메터로 다른 함수에 전달 할 수 있습니다. 이것을 콜백함수라고 합니다.
You can pass a lambda function like the one above as a parameter to another function. This is called a callback function.
my_sv.set_handler([&](const std::string& req) -> std::string {
return router(req);
});
👉🏻 람다함수에서 [&] 이것을 캡춰리스트라고 합니다.
In lambda functions, [&] is called a capture list.
👉🏻 캡춰 리스트에는 다음과 같은 종류가 있습니다.
The capture list includes the following types.
| 구문/Syntax | 의미/Meaning | 특징/Features | 사용 예시/Usage Examples |
|---|---|---|---|
[] | 아무것도 캡처하지 않음 / Capturing nothing | 캡처할 외부 변수가 없을 때 사용 / Used when there are no external variables to capture. | [](){ ... } |
[var1, var2] | 특정 변수만 명시적 캡처 / Explicitly capture only specific variables | 필요한 변수만 골라 가져올 때 / When selecting and retrieving only the necessary variables | [i, j]() |
[=] | 모든 외부 변수를 값으로 복사 / Copy all external variables by value | 현재 범위의 모든 변수를 값으로 복사하여 사용합니다. / Copy all variables in the current range by value and use them. | [=]() |
[&] | 모든 외부 변수를 참조로 사용 / Use all external variables by reference | 현재 범위의 모든 변수를 참조로 사용합니다. / Uses all variables in the current range as references. | [&]() |
[&var] | 특정 변수를 참조로 캡처 / Capturing a specific variable by reference | 원하는 변수만 지정하여 참조로 사용할 때 / When using references by specifying only the desired variables | [&i]() |
👉🏻 캡춰 리스트의 범위는 main()함수 전체 범위 입니다.
The range of the capture list is the entire range of the main() function.
👉🏻 -> std::string 이 부분은 반환되는 값의 타입입니다.
-> std::string This part is the type of the returned value.
👉🏻코드 / Code
✔️ 아래는 람다함수와 콜백함수 패턴을 사용해서 자주 구현되는 코드 패턴중의 하나입니다.
Below is one of the code patterns frequently implemented using lambda functions and callback function patterns.
✔️ main.cpp
#include <iostream>
#include <string>
#include <functional>
#include <vector>
class Server {
public:
// 로직을 담을 함수 저장소 (람다를 담는 그릇)
// Function repository to hold logic (container for Lambda)
std::function<std::string(const std::string&)> logic_handler;
// 핸들러 설정 메서드(logic_handler에서 외부 함수 handler 연결)
// handler함수에는 익명함수로써 문자열 입력받고 router함수 리턴
// Handler configuration method (connecting the external function handler in logic_handler)
// The handler function receives a string as an anonymous function and returns the router function
void set_handler(std::function<std::string(const std::string&)> handler) {
logic_handler = handler;
}
// 클라이언트 요청을 처리하는 가상 메서드
// Virtual method that handles client requests
void receive_request(const std::string& message) {
std::cout << "[Server] 요청 받음 / Requested: " << message << std::endl;
if (logic_handler) {
// 외부에서 정의한 람다 함수가 여기서 실행됩니다!
// login_handler는 router 함수의 값을 리턴
// The externally defined Lambda function is executed here!
// login_handler returns the value of the router function
std::string response = logic_handler(message);
std::cout << "[Server] 응답 보냄 / Reply sent: " << response << "\n" << std::endl;
} else {
std::cout << "[Server] 처리할 핸들러가 없습니다/There is no handler to process..\n" << std::endl;
}
}
};
std::string router(const std::string& msg) {
if (msg == "aloy") return "horizon";
if (msg == "silverhand") return "cyberpunk";
return "unknown command";
}
int main() {
Server my_sv;
// 람다 함수를 사용하여 로직 연결 / Connecting logic using lambda functions
my_sv.set_handler([&](const std::string& req) -> std::string {
return router(req);
});
// 요청 / requests
my_sv.receive_request("aloy");
my_sv.receive_request("silverhand");
my_sv.receive_request("npc");
return 0;
}
✔️ 컴파일 / Compiling
g++ main.cpp -o main -std=c++17
✔️ 실행 / Run
./main
✔️ 결과 / Resutl
rambda_function % ./main
[Server] 요청 받음: aloy
[Server] 응답 보냄/Reply sent: horizon
[Server] 요청 받음: silverhand
[Server] 응답 보냄/Reply sent: cyberpunk
[Server] 요청 받음: npc
[Server] 응답 보냄/Reply sent: unknown command