C++ std::bind, cref, placeholders, function

Intro

std::function, bind, placeholders 알아보기

std::bind

std::bind는 기존의 함수를 이용하여 새로운 함수를 정의 할수 있다.

예시

#include <functional>
#include <iostream>

using namespace std;

int multiple(int a, int b)
{
	return a * b;
}

int main()
{
	auto func1 = std::bind(multiple, 5, 10);
	auto func2 = std::bind(multiple, 2, 5);

	cout << func1() << " " << func2() << endl;
}

기존 곱셈을 하는 multiple 함수를 std::bind를 이용하여 func1, func2 함수를 만든 예제.

이외에도 다음과 같이 변수를 이용해 바인딩 할 수 있다.

int a = 10;
int b = 2;

auto func3 = std::bind(multiple, a, b); // 호출되는 시점의 변수 값으로 바인딩된다
	
	
cout << func3() << endl;

a = 20;
b = 5;

cout << func3() << endl;

// 결과 20, 20 이 나온다

바인딩 한다음에 변수 값을 변경해도 바인딩된 값이 변하지 않는다.

하지만 다음과 같이 std::cref()를 이용하여 변수의 레퍼런스를 넘겨준다면 바인딩된 값도 바뀌게된다.

int a = 10;
int b = 2;

auto func3 = std::bind(multiple, std::cref(a), std::cref(b)); 
cout << func3() << endl;

a = 20;
b = 5;

cout << func3() << endl;
// 결과 20, 100

std::placeholders

std::placeholders를 이용하면 사용자의 입력에의한 함수를 만들 수있다.

예시

int multiple(int a, int b)
{
	return a * b;
}

int main()
{
    auto func4 = std::bind(multiple, 10, std::placeholders::_1)
    
    cout<<func4(5)<<endl;
    
    // 결과 50
}

std::function

std::function은 일종의 함수포인터의 확장 개념이며 다음과 같이 사용한다.

#include <functional>

std::function<리턴타입(입력 파라미터)> 변수이름

std::function이 호출 할 수있는 함수는 다음과 같다.

  • 일반함수

  • Lambda 함수

  • std::bind 반환 값

  • 함수 객체

  • class의 멤버함수, 멤버변수

  • Functor

예시

#include <functional>
#include <iostream>

using namespace std;

int multiple(int a, int b)
{
	return a * b;
}

int main()
{
	// 일반함수
	std::function<int(int,int)> f1 = multiple;
	cout << f1(10, 100) << endl;

	// 람다함수 
	std::function<int(int, int)> f2 = [](int a,int b)->int { return multiple(a,b); };
	cout << f2(20, 20) << endl;

	// std::bind
	std::function<int(int, int)> f3 = std::bind(multiple, std::placeholders::_1, std::placeholders::_2);
	cout << f3(30,30) << endl;
}

태그: ,

카테고리:

업데이트:

댓글남기기