C++ bind | "함수 바인딩" 가이드
이 글의 핵심
std::bind 는 C++11에서 도입된 함수로, 함수와 인자를 미리 바인딩하여 새로운 함수 객체를 생성합니다. 부분 적용(Partial Application), 인자 재배치, 멤버 함수 바인딩 등에 사용됩니다.
bind란?
std::bind 는 C++11에서 도입된 함수로, 함수와 인자를 미리 바인딩하여 새로운 함수 객체를 생성합니다. 부분 적용(Partial Application), 인자 재배치, 멤버 함수 바인딩 등에 사용됩니다.
왜 필요한가?:
- 부분 적용: 일부 인자를 미리 고정
- 인자 재배치: 인자 순서 변경
- 멤버 함수: 멤버 함수를 일반 함수처럼 사용
- 콜백: 콜백 함수 생성
// ❌ 직접 구현: 번거로움
class Add5 {
int fixed_;
public:
Add5(int fixed) : fixed_(fixed) {}
int operator()(int x) const { return fixed_ + x; }
};
Add5 add5(5);
add5(10); // 15
// ✅ bind: 간결
auto add5 = std::bind(add, 5, std::placeholders::_1);
add5(10); // 15
기본 사용법
#include <functional>
using namespace std;
using namespace placeholders;
int add(int a, int b) {
return a + b;
}
int main() {
// 부분 적용
auto add5 = bind(add, 5, _1);
cout << add5(10) << endl; // 15
cout << add5(20) << endl; // 25
}
bind의 동작 원리:
// 개념적 구현
template<typename Func, typename... BoundArgs>
class BindExpression {
Func func_;
std::tuple<BoundArgs...> boundArgs_;
public:
BindExpression(Func func, BoundArgs... args)
: func_(func), boundArgs_(args...) {}
template<typename... CallArgs>
auto operator()(CallArgs&&... args) {
// boundArgs와 args를 조합하여 func 호출
return std::apply(func_, /* 조합된 인자 */);
}
};
placeholders
int subtract(int a, int b) {
return a - b;
}
int main() {
// 인자 순서 그대로
auto f1 = bind(subtract, _1, _2);
cout << f1(10, 3) << endl; // 7
// 인자 순서 바꾸기
auto f2 = bind(subtract, _2, _1);
cout << f2(10, 3) << endl; // -7 (3 - 10)
// 고정 인자
auto f3 = bind(subtract, 100, _1);
cout << f3(30) << endl; // 70
}
멤버 함수
class Calculator {
public:
int multiply(int a, int b) const {
return a * b;
}
int value = 10;
};
int main() {
Calculator calc;
// 멤버 함수 바인딩
auto f = bind(&Calculator::multiply, &calc, _1, _2);
cout << f(3, 4) << endl; // 12
// 멤버 변수 바인딩
auto getValue = bind(&Calculator::value, &calc);
cout << getValue() << endl; // 10
}
실전 예시
예시 1: 이벤트 핸들러
class Button {
private:
function<void()> onClick;
public:
void setOnClick(function<void()> handler) {
onClick = handler;
}
void click() {
if (onClick) {
onClick();
}
}
};
class App {
public:
void handleClick(const string& buttonName) {
cout << buttonName << " 클릭됨" << endl;
}
};
int main() {
App app;
Button btn;
// 멤버 함수 바인딩
btn.setOnClick(bind(&App::handleClick, &app, "버튼1"));
btn.click(); // "버튼1 클릭됨"
}
예시 2: 부분 적용
int power(int base, int exponent) {
int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
int main() {
// 제곱 함수
auto square = bind(power, _1, 2);
cout << square(5) << endl; // 25
// 세제곱 함수
auto cube = bind(power, _1, 3);
cout << cube(5) << endl; // 125
// 2의 거듭제곱
auto powerOf2 = bind(power, 2, _1);
cout << powerOf2(10) << endl; // 1024
}
예시 3: 필터 조합
bool inRange(int value, int min, int max) {
return value >= min && value <= max;
}
int main() {
vector<int> v = {1, 5, 10, 15, 20, 25, 30};
// 10-20 범위 필터
auto filter = bind(inRange, _1, 10, 20);
auto it = find_if(v.begin(), v.end(), filter);
if (it != v.end()) {
cout << "첫 매칭: " << *it << endl; // 10
}
// 모두 찾기
for (int x : v) {
if (filter(x)) {
cout << x << " "; // 10 15 20
}
}
}
예시 4: 콜백 시스템
class Timer {
private:
function<void()> callback;
public:
void setCallback(function<void()> cb) {
callback = cb;
}
void trigger() {
if (callback) {
callback();
}
}
};
class Logger {
public:
void log(const string& level, const string& message) {
cout << "[" << level << "] " << message << endl;
}
};
int main() {
Timer timer;
Logger logger;
// 부분 적용
timer.setCallback(bind(&Logger::log, &logger, "INFO", "타이머 실행"));
timer.trigger(); // [INFO] 타이머 실행
}
bind vs 람다
// bind
auto f1 = bind(add, 5, _1);
// 람다 (더 명확)
auto f2 = { return add(5, x); };
int main() {
cout << f1(10) << endl; // 15
cout << f2(10) << endl; // 15
}
람다 장점:
- 더 읽기 쉬움
- 타입 추론
- 컴파일 에러 명확
bind 장점:
- 인자 재배치
- 멤버 포인터 간편
자주 발생하는 문제
문제 1: 참조 바인딩
int x = 10;
// ❌ 복사
auto f1 = bind(add, x, _1);
x = 20;
cout << f1(5) << endl; // 15 (x=10 복사됨)
// ✅ 참조
auto f2 = bind(add, ref(x), _1);
x = 20;
cout << f2(5) << endl; // 25 (x=20 참조)
문제 2: placeholder 순서
// ❌ 헷갈림
auto f = bind(subtract, _2, _1); // 순서 바뀜
cout << f(10, 3) << endl; // -7 (3 - 10)
// ✅ 람다 (명확)
auto f2 = { return subtract(b, a); };
cout << f2(10, 3) << endl; // -7
문제 3: 중첩 bind
// ❌ 복잡
auto f = bind(add, bind(multiply, _1, 2), _2);
// ✅ 람다 (명확)
auto f2 = { return add(multiply(x, 2), y); };
실무 패턴
패턴 1: 비교 함수 커스터마이징
struct Person {
std::string name;
int age;
};
bool compareByAge(const Person& a, const Person& b) {
return a.age < b.age;
}
bool compareByName(const Person& a, const Person& b) {
return a.name < b.name;
}
// 사용
std::vector<Person> people = {
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35}
};
// 나이순 정렬
std::sort(people.begin(), people.end(), compareByAge);
// 이름순 정렬
std::sort(people.begin(), people.end(), compareByName);
패턴 2: 스레드 콜백
class Worker {
public:
void process(int id, const std::string& task) {
std::cout << "Worker " << id << ": " << task << '\n';
}
};
// 사용
Worker worker;
// 멤버 함수를 스레드에 전달
std::thread t1(std::bind(&Worker::process, &worker, 1, "Task A"));
std::thread t2(std::bind(&Worker::process, &worker, 2, "Task B"));
t1.join();
t2.join();
패턴 3: 함수 어댑터
int divide(int a, int b) {
return a / b;
}
// 인자 순서 바꾸기
auto divideBy = {
return std::bind(divide, std::placeholders::_1, divisor);
};
// 사용
auto divideBy2 = divideBy(2);
auto divideBy10 = divideBy(10);
std::cout << divideBy2(100) << '\n'; // 50
std::cout << divideBy10(100) << '\n'; // 10
FAQ
Q1: bind는 언제 사용하나요?
A:
- 부분 적용: 일부 인자를 미리 고정
- 멤버 함수 바인딩: 멤버 함수를 일반 함수처럼 사용
- 인자 재배치: 인자 순서 변경
// 부분 적용
auto add5 = std::bind(add, 5, std::placeholders::_1);
// 멤버 함수
auto f = std::bind(&Calculator::multiply, &calc, std::placeholders::_1, std::placeholders::_2);
Q2: bind vs 람다?
A: 대부분 람다가 더 명확합니다. bind는 특수한 경우만 사용합니다.
// bind: 복잡
auto f1 = std::bind(add, 5, std::placeholders::_1);
// 람다: 명확 (권장)
auto f2 = { return add(5, x); };
람다 권장 이유:
- 더 읽기 쉬움
- 타입 추론이 명확
- 컴파일 에러가 명확
Q3: 성능 오버헤드는?
A: 인라인화로 오버헤드 거의 없음.
auto f = std::bind(add, 5, std::placeholders::_1);
f(10); // 컴파일러가 인라인화 → add(5, 10)과 동일
Q4: 참조 바인딩은 어떻게 하나요?
A: std::ref() 또는 std::cref() 를 사용합니다.
int x = 10;
// ❌ 복사
auto f1 = std::bind(add, x, std::placeholders::_1);
x = 20;
f1(5); // 15 (x=10 복사됨)
// ✅ 참조
auto f2 = std::bind(add, std::ref(x), std::placeholders::_1);
x = 20;
f2(5); // 25 (x=20 참조)
Q5: bind는 deprecated인가요?
A: 아니지만, C++11 이후 람다를 더 권장합니다.
// bind: 여전히 유효하지만...
auto f1 = std::bind(add, 5, std::placeholders::_1);
// 람다: 더 권장
auto f2 = { return add(5, x); };
Q6: placeholder는 무엇인가요?
A: 호출 시 전달될 인자의 위치를 나타냅니다.
using namespace std::placeholders;
// _1: 첫 번째 인자
auto f1 = std::bind(add, 5, _1);
f1(10); // add(5, 10)
// _2: 두 번째 인자
auto f2 = std::bind(subtract, _2, _1);
f2(10, 3); // subtract(3, 10)
Q7: 중첩 bind는 가능한가요?
A: 가능하지만 복잡합니다. 람다를 권장합니다.
// ❌ 중첩 bind: 복잡
auto f = std::bind(add, std::bind(multiply, _1, 2), _2);
// ✅ 람다: 명확
auto f2 = { return add(multiply(x, 2), y); };
Q8: bind 학습 리소스는?
A:
- cppreference.com - std::bind
- “Effective Modern C++” by Scott Meyers (Item 34)
- “The C++ Standard Library” by Nicolai Josuttis
관련 글: lambda, function, placeholders.
한 줄 요약: std::bind는 함수와 인자를 미리 바인딩하여 새로운 함수 객체를 생성하는 C++11 함수입니다.
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ initializer_list | “초기화 리스트” 가이드
- C++ Universal Reference | “유니버설 레퍼런스” 가이드
- C++ auto 키워드 | “타입 추론” 가이드
관련 글
- C++ async & launch |
- C++ Atomic Operations |
- C++ Attributes |
- C++ auto 키워드 |
- C++ auto 타입 추론 | 복잡한 타입을 컴파일러에 맡기기