• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

placeholder

22.02.11 14:11 작성 조회수 736

0

bind, placeholder라는 개념이 잘 이해가 안되는데요!

1. bind를 사용하는 이유가 무엇인가요?
2. placeholder의 의미가 무엇인가요?

답변 1

답변을 작성해보세요.

5

강민철님의 프로필

강민철

2022.02.11

안녕하세요 :)

 

std::bind

bind를 사용하는 이유는 함수에 인자를 바인딩(함수에 사용될 인자를 매칭시키는 것)하기 위함입니다.

아래 예시를 보세요.

 

#include<iostream>
#include<string>
#include<functional>

using namespace std;

void hello(const string& s)
{
	cout << s << endl;
}

int main()
{
	auto func = std::bind(hello, "hello world");
	func();
}

위 코드의 실행 결과는 hello world입니다.

즉, func()를 호출하면 hello world가 출력됩니다.

hello 함수에 "hello world" 라는 인자를 바인딩 해주었기 때문입니다.

 

std::placeholders

placeholders는 bind에서 사용할 인자를 대체하기 위해 사용됩니다.

이 말이 조금 어색할 수 있겠으나, 이 또한 예시 코드로 이해하는 것이 좋습니다.

아래 예시를 보세요.

#include<iostream>
#include<string>
#include<functional>

using namespace std;

int sum(int a, int b, int c)
{
	return a + b + c;
}

int main()
{
	auto func1 = std::bind(sum, placeholders::_1, 2, 3);
	cout << func1(1) << endl;

}

// 실행 결과 6

위 예시 코드에서 func1을 호출할 적에 두 번째 인자와 세 번째 인자는 각각 2와 3으로 고정된 채 placeholders::_1 자리에 들어갈 인자만 넣으면 됩니다.

#include<iostream>
#include<string>
#include<functional>

using namespace std;

int sum(int a, int b, int c)
{
	return a + b + c;
}

int main()

{	
	auto func2 = std::bind(sum, placeholders::_1, placeholders::_2, 3);
	cout << func2(2, 3) << endl;
}

// 실행 결과 8

위 예시에서는 func1을 호출할 적에 세 번째 인자는 3으로 고정된 채

placeholders::_1, placeholders::_2 자리에 들어갈 인자만 넣으면 됩니다.

#include<iostream>
#include<string>
#include<functional>

using namespace std;

int sum(int a, int b, int c)
{
	return a + b + c;
}

int main()

{	
	auto func2 = std::bind(sum, placeholders::_1, placeholders::_2, placeholders::_3);
	cout << func2(2, 3, 4) << endl;
}

// 실행 결과 9

위 예시는 func1을 호출할 적에 

placeholders::_1, placeholders::_2, placeholders::_3 자리에 들어갈 인자만 넣으면 됩니다.

(물론 이렇게는 잘 사용하지 않습니다)

 

처음 binding과 placeholders를 접하면 잘 와닿지 않을 수 있다고 생각합니다.

이 두 개념은 말로써 이해하는 것이 아닌 

다양한 예시 코드로써 이해해보시는 것을 추천드립니다.

 

감사합니다.

 

박제영님의 프로필

박제영

2024.05.16

쉽게 이해할 수 있었습니다. 간단 명료한 답변 감사드립니다.