- 함수란?
함수는 input을 받아서 특정 컴퓨터 연산을 수행하고 output을 생산하는 집합체이다.
- 함수를 사용하는 이유
함수를 사용하는 이유는 공통적이고 반복적인 작업을 함께 수행하기 위함이다. 즉, 각 input에 따라 같은 코드를 반복적으로 작성하는 것을 피하기 위해서 함수를 사용한다.
- 함수의 형태
일반적인 함수의 형태는 아래와 같다.
return_type function_name([ arg1_type arg1_name, ... ])
{
// Perform Operations
}
함수를 매개변수로 전달하는 것은 C++에서 매우 유용한 개념이다. 이 개념은 std::sort() 함수에서 커스텀 비교 함수를 매개변수로 전달할 때부터 사용해왔다. 이 게시글에서 우리는 다른 함수를 매개변수로 전달받는 함수를 설계하는 방법들을 논의해볼 것이다.
함수를 매개변수로 전달하는 3가지 방법
1. 포인터로 전달
2. std::function<> 사용
3. 람다 사용
1. 함수 포인터로 전달하기
함수는 다른 함수의 주소를 포인터로 받아서 전달할 수 있다.
예제
// C++ program to pass function as a
// pointer to any function
#include <iostream>
using namespace std;
// Function that add two numbers
int add(int x, int y) { return x + y; }
// Function that multiplies two
// numbers
int multiply(int x, int y) { return x * y; }
// Function that takes a pointer
// to a function
int invoke(int x, int y, int (*func)(int, int))
{
return func(x, y);
}
// Driver Code
int main()
{
// Pass pointers to add & multiply
// function as required
cout << "Addition of 20 and 10 is ";
cout << invoke(20, 10, &add) << '\n';
cout << "Multiplication of 20"
<< " and 10 is ";
cout << invoke(20, 10, &multiply) << '\n';
return 0;
}
실행 결과
Addition of 20 and 10 is 30
Multiplication of 20 and 10 is 200
2. std::function<> 사용하기
c++11부터는 std::function<>이라는 template 클래스를 제공해준다. 이건 함수를 객체 형태로 전달할 수 있게 해준다. std::function<>의 객체는 아래와 같이 생성될 수 있다.
std::function<return_type(arg1_type, arg2-type...)> obj_name
// This object can be use to call the function as below
return_type catch_variable = obj_name(arg1, arg2);
예제
// C++ program to demonstrate the passing
// of functions as an object parameter
#include <functional>
#include <iostream>
using namespace std;
// Define add and multiply to
// return respective values
int add(int x, int y) { return x + y; }
int multiply(int x, int y) { return x * y; }
// Function that accepts an object of
// type std::function<> as a parameter
// as well
int invoke(int x, int y, function<int(int, int)> func)
{
return func(x, y);
}
// Driver code
int main()
{
// Pass the required function as
// parameter using its name
cout << "Addition of 20 and 10 is ";
cout << invoke(20, 10, &add) << '\n';
cout << "Multiplication of 20"
<< " and 10 is ";
cout << invoke(20, 10, &multiply) << '\n';
return 0;
}
실행 결과
Addition of 20 and 10 is 30
Multiplication of 20 and 10 is 200
3.람다 사용하기
c++에서 람다는 두 가지 방식으로 정의할 수 있다. 하나는 inline으로 정의하는 것이고, 다른 하나는 익명의 함수 객체로 정의하는 것이다. 여기 예제에서 람다는 우리가 매개변수로 전달할 위치에 정의하고 있다.
예제
// C++ program to pass the function as
// parameter as a lambda expression
#include <functional>
#include <iostream>
using namespace std;
// Function that takes a pointer
// to a function
int invoke(int x, int y,
function<int(int, int)> func)
{
return func(x, y);
}
// Driver Code
int main()
{
// Define lambdas for addition and
// multiplication operation where
// we want to pass another function
// as a parameter
// Perform Addition
cout << "Addition of 20 and 10 is ";
int k = invoke(20, 10,
[](int x,
int y) -> int {
return x + y;
});
cout << k << '\n';
// Perform Multiplication
cout << "Multiplication of 20"
<< " and 10 is ";
int l = invoke(20, 10,
[](int x,
int y) -> int {
return x * y;
});
cout << l << '\n';
return 0;
}
실행 결과
Addition of 20 and 10 is 30
Multiplication of 20 and 10 is 200
geeksforgeeks 번역하기
출처: https://www.geeksforgeeks.org/passing-a-function-as-a-parameter-in-cpp/