C++ std::bind | Placeholders and partial application
이 글의 핵심
std::bind is a function introduced in C++11 that creates a new function object by pre-binding a function and its arguments. It is used for partial application, argument relocation, member function binding, etc.
What is bind?
std::bind is a function introduced in C++11 that creates a new function object by prebinding a function and its arguments. Used for partial application, argument relocation, member function binding, etc.
Why do you need it?:
- Partially applied: Some parameters are fixed in advance
- Argument Relocation: Change the order of arguments
- Member function: Use member functions like regular functions
- Callback: Create a callback function```cpp // ❌ 직접 구현: 번거로움 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
## Basic usagecpp
#include
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
}
How bind works:cpp
// 개념적 구현
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
```cpp
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
}
```## Member function```cpp
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
}
```## Practical example
### Example 1: Event handler```cpp
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 클릭됨"
}
```### Example 2: Partial application```cpp
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
}
```### Example 3: Filter Combination```cpp
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
}
}
}
```### Example 4: Callback system```cpp
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 lambda```cpp
// 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
}
```Lambda Advantages:
- Easier to read
- Type inference
- Clear compilation errors
bind advantages:
- Argument relocation
- Simple member pointer
## Frequently occurring problems
### Issue 1: Reference binding```cpp
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 참조)
```### Problem 2: Placeholder order```cpp
// ❌ 헷갈림
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
```### Problem 3: Nested bind```cpp
// ❌ 복잡
auto f = bind(add, bind(multiply, _1, 2), _2);
// ✅ 람다 (명확)
auto f2 = { return add(multiply(x, 2), y); };
```## Practice pattern
### Pattern 1: Customizing the comparison function```cpp
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);
```### Pattern 2: Thread callback```cpp
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();
```### Pattern 3: Function adapter```cpp
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: When do you use bind?
A:
- Partially applied: Some parameters are fixed in advance
- Member function binding: Use member functions like regular functions
- Argument Relocation: Change the order of arguments```cpp
// 부분 적용
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 lambda?
A: Most lambdas are clearer. bind is only used in special cases.```cpp
// bind: 복잡
auto f1 = std::bind(add, 5, std::placeholders::_1);
// 람다: 명확 (권장)
auto f2 = { return add(5, x); };
```Why Lambda is recommended:
- Easier to read
- Clear type inference
- Compilation errors are clear
### Q3: What is the performance overhead?
A: Almost no overhead due to inlining.```cpp
auto f = std::bind(add, 5, std::placeholders::_1);
f(10); // 컴파일러가 인라인화 → add(5, 10)과 동일
```### Q4: How do I bind references?
A: Use `std::ref()` or `std::cref()`.```cpp
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: Is bind deprecated?
A: No, but lambda is more recommended after C++11.```cpp
// bind: 여전히 유효하지만...
auto f1 = std::bind(add, 5, std::placeholders::_1);
// 람다: 더 권장
auto f2 = { return add(5, x); };
```### Q6: What is a placeholder?
A: Indicates the position of the argument to be passed when calling.```cpp
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: Is nested bind possible?
A: It's possible, but it's complicated. I recommend lambda.```cpp
// ❌ 중첩 bind: 복잡
auto f = std::bind(add, std::bind(multiply, _1, 2), _2);
// ✅ 람다: 명확
auto f2 = { return add(multiply(x, 2), y); };
```### Q8: What are bind learning resources?
A:
- [cppreference.com - std::bind](https://en.cppreference.com/w/cpp/utility/functional/bind)
- "Effective Modern C++" by Scott Meyers (Item 34)
- "The C++ Standard Library" by Nicolai Josuttis
Related article: lambda, function, placeholders.
One-line summary: `std::bind` is a C++11 function that creates a new function object by prebinding a function and its arguments.
---
## Good article to read together (internal link)
Here's another article related to this topic.
- [C++ initializer_list | “Initializer List” Guide](/blog/cpp-initializer-list/)
- [C++ Universal Reference | “Universal Reference” guide](/blog/cpp-universal-reference/)
- [C++ auto keyword | “Type Inference” Guide](/blog/cpp-auto-keyword/)
## Practical tips
These are tips that can be applied right away in practice.
### Debugging tips
- If you run into a problem, check the compiler warnings first.
- Reproduce the problem with a simple test case
### Performance Tips
- Don't optimize without profiling
- Set measurable indicators first
### Code review tips
- Check in advance for areas that are frequently pointed out in code reviews.
- Follow your team's coding conventions
---
## Practical checklist
This is what you need to check when applying this concept in practice.
### Before writing code
- [ ] Is this technique the best way to solve the current problem?
- [ ] Can team members understand and maintain this code?
- [ ] Does it meet the performance requirements?
### Writing code
- [ ] Have you resolved all compiler warnings?
- [ ] Have you considered edge cases?
- [ ] Is error handling appropriate?
### When reviewing code
- [ ] Is the intent of the code clear?
- [ ] Are there enough test cases?
- [ ] Is it documented?
Use this checklist to reduce mistakes and improve code quality.
---
## Keywords covered in this article (related search terms)
This article will be helpful if you search for C++, bind, C++11, functional, placeholder, etc.
---
## Related articles
- [C++ async & launch | ](/blog/cpp-async-launch/)
- [C++ Atomic Operations | ](/blog/cpp-atomic-operations/)
- [C++ Attributes | ](/blog/cpp-attributes/)
- [C++ auto keyword | ](/blog/cpp-auto-keyword/)
- [C++ auto type inference | [Leaving complex types to the compiler](/blog/cpp-auto-type-deduction/)