C++ function objects | Functors, operator(), and STL algorithms

C++ function objects | Functors, operator(), and STL algorithms

이 글의 핵심

Functors, operator(), comparison with function pointers, STL algorithms, and std::function performance tradeoffs.

What is a function object?

Functor is a class that overloads operator(). It can be called like a function and can maintain state, making it more flexible than regular functions.```cpp struct Adder { int operator()(int a, int b) const { return a + b; } };

int main() { Adder add;

cout << add(2, 3) << endl;  // 5
cout << add(10, 20) << endl;  // 30

}

- State retention: Save state between function calls
- Inline Optimization: Faster than function pointers
- STL Compatible: Used with STL algorithms
- Type safety: Compile-time type checking```cpp
// ❌ 함수 포인터: 상태 유지 불가
int counter = 0;
void increment() {
    counter++;
}

// ✅ 함수 객체: 상태 유지
class Counter {
    int count_ = 0;
public:
    int operator()() {
        return ++count_;
    }
};

Counter counter;
counter();  // 1
counter();  // 2
```Function object vs function pointer:

| Features | function pointer | function object |
|------|-------------|--------------------------|
| Stay status | ❌ Not possible | ✅ Available |
| Inline Optimization | ❌ Difficulty | ✅ Available |
| Type Safe | ✅ Available | ✅ Available |
| Flexibility | ❌ Low | ✅ High |
| Performance | slow | Fast |```cpp
// 함수 포인터: 간접 호출
int (*funcPtr)(int, int) = add;
funcPtr(2, 3);  // 간접 호출

// 함수 객체: 인라인 가능
Adder adder;
adder(2, 3);  // 인라인 가능
```## Maintain state```cpp
class Counter {
private:
    int count = 0;
    
public:
    int operator()() {
        return ++count;
    }
    
    int getCount() const {
        return count;
    }
};

int main() {
    Counter counter;
    
    cout << counter() << endl;  // 1
    cout << counter() << endl;  // 2
    cout << counter() << endl;  // 3
    
    cout << "총 호출: " << counter.getCount() << endl;
}
```## STL algorithm```cpp
#include <algorithm>

struct IsEven {
    bool operator()(int x) const {
        return x % 2 == 0;
    }
};

int main() {
    vector<int> v = {1, 2, 3, 4, 5, 6};
    
    // count_if
    int evenCount = count_if(v.begin(), v.end(), IsEven());
    cout << "짝수 개수: " << evenCount << endl;
    
    // remove_if
    v.erase(remove_if(v.begin(), v.end(), IsEven()), v.end());
    
    for (int x : v) {
        cout << x << " ";  // 1 3 5
    }
}
```## Practical example

### Example 1: Comparison function```cpp
struct Person {
    string name;
    int age;
};

struct CompareByAge {
    bool operator()(const Person& a, const Person& b) const {
        return a.age < b.age;
    }
};

struct CompareByName {
    bool operator()(const Person& a, const Person& b) const {
        return a.name < b.name;
    }
};

int main() {
    vector<Person> people = {
        {"Charlie", 30},
        {"Alice", 25},
        {"Bob", 35}
    };
    
    // 나이순 정렬
    sort(people.begin(), people.end(), CompareByAge());
    
    for (const auto& p : people) {
        cout << p.name << " (" << p.age << ")" << endl;
    }
}
```### Example 2: Filter```cpp
class RangeFilter {
private:
    int min, max;
    
public:
    RangeFilter(int min, int max) : min(min), max(max) {}
    
    bool operator()(int value) const {
        return value >= min && value <= max;
    }
};

int main() {
    vector<int> v = {1, 5, 10, 15, 20, 25, 30};
    
    // 10-20 범위
    RangeFilter filter(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 << " ";
        }
    }
}
```### Example 3: Accumulator```cpp
class Accumulator {
private:
    int sum = 0;
    
public:
    void operator()(int value) {
        sum += value;
    }
    
    int getSum() const {
        return sum;
    }
};

int main() {
    vector<int> v = {1, 2, 3, 4, 5};
    
    Accumulator acc = for_each(v.begin(), v.end(), Accumulator());
    
    cout << "합계: " << acc.getSum() << endl;  // 15
}
```### Example 4: Converter```cpp
class Multiplier {
private:
    int factor;
    
public:
    Multiplier(int f) : factor(f) {}
    
    int operator()(int value) const {
        return value * factor;
    }
};

int main() {
    vector<int> v = {1, 2, 3, 4, 5};
    vector<int> result(v.size());
    
    transform(v.begin(), v.end(), result.begin(), Multiplier(10));
    
    for (int x : result) {
        cout << x << " ";  // 10 20 30 40 50
    }
}
```## Standard function object```cpp
#include <functional>

int main() {
    vector<int> v = {3, 1, 4, 1, 5};
    
    // plus
    int sum = accumulate(v.begin(), v.end(), 0, plus<int>());
    cout << sum << endl;  // 14
    
    // greater (내림차순)
    sort(v.begin(), v.end(), greater<int>());
    
    for (int x : v) {
        cout << x << " ";  // 5 4 3 1 1
    }
}
```## Function object vs lambda```cpp
// 함수 객체
struct Adder {
    int factor;
    Adder(int f) : factor(f) {}
    int operator()(int x) const { return x + factor; }
};

// 람다 (간결)
auto adder = [factor = 10](int x) { return x + factor; };

int main() {
    Adder add10(10);
    cout << add10(5) << endl;  // 15
    
    cout << adder(5) << endl;  // 15
}
```Function Object Advantages:
- Explicit type
- Reusable
- Clear status management

Lambda Advantages:
- brevity
- Inline definition
- Type inference

## Frequently occurring problems

### Issue 1: Missing const```cpp
// ❌ const 없음
struct Adder {
    int operator()(int x) {  // const 없음
        return x + 10;
    }
};

// STL 알고리즘에서 문제 발생 가능

// ✅ const 추가
struct Adder {
    int operator()(int x) const {
        return x + 10;
    }
};
```### Problem 2: State change```cpp
// 상태 변경 시 const 제거
class Counter {
private:
    mutable int count = 0;  // mutable
    
public:
    int operator()() const {
        return ++count;
    }
};
```### Issue 3: Copy costs```cpp
// ❌ 큰 상태
struct HeavyFunctor {
    vector<int> data;  // 큰 데이터
    
    int operator()(int x) const {
        // ...
    }
};

// STL 알고리즘이 복사할 수 있음

// ✅ ref 사용
HeavyFunctor heavy;
for_each(v.begin(), v.end(), ref(heavy));
```## Practice pattern

### Pattern 1: Gather statistics```cpp
class Statistics {
    int count_ = 0;
    int sum_ = 0;
    int min_ = INT_MAX;
    int max_ = INT_MIN;
    
public:
    void operator()(int value) {
        count_++;
        sum_ += value;
        min_ = std::min(min_, value);
        max_ = std::max(max_, value);
    }
    
    double average() const {
        return count_ > 0 ? static_cast<double>(sum_) / count_ : 0.0;
    }
    
    int min() const { return min_; }
    int max() const { return max_; }
    int count() const { return count_; }
};

// 사용
std::vector<int> data = {10, 20, 30, 40, 50};
Statistics stats = std::for_each(data.begin(), data.end(), Statistics());

std::cout << "평균: " << stats.average() << '\n';  // 30
std::cout << "최소: " << stats.min() << '\n';      // 10
std::cout << "최대: " << stats.max() << '\n';      // 50
```### Pattern 2: Conditional transformation```cpp
class ConditionalTransform {
    std::function<bool(int)> predicate_;
    std::function<int(int)> transform_;
    
public:
    ConditionalTransform(
        std::function<bool(int)> pred,
        std::function<int(int)> trans
    ) : predicate_(pred), transform_(trans) {}
    
    int operator()(int value) const {
        if (predicate_(value)) {
            return transform_(value);
        }
        return value;
    }
};

// 사용
std::vector<int> v = {1, 2, 3, 4, 5, 6};

// 짝수만 2배
auto transformer = ConditionalTransform(
     { return x % 2 == 0; },
     { return x * 2; }
);

std::transform(v.begin(), v.end(), v.begin(), transformer);
// 결과: 1, 4, 3, 8, 5, 12
```### Pattern 3: Caching functions```cpp
template<typename Func>
class Memoized {
    Func func_;
    mutable std::map<int, int> cache_;
    
public:
    Memoized(Func func) : func_(func) {}
    
    int operator()(int x) const {
        if (auto it = cache_.find(x); it != cache_.end()) {
            return it->second;
        }
        
        int result = func_(x);
        cache_[x] = result;
        return result;
    }
};

// 사용
int fibonacci(int n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

Memoized<int(*)(int)> fib(fibonacci);
std::cout << fib(40) << '\n';  // 빠름 (캐시)
```## FAQ

### Q1: When do you use function objects?

A: 
- State retention: Save state between function calls
- STL algorithm: `sort`, `find_if`, `transform`, etc.
- Custom Compare/Filter: Complex logic```cpp
class RangeFilter {
    int min_, max_;
public:
    RangeFilter(int min, int max) : min_(min), max_(max) {}
    bool operator()(int x) const { return x >= min_ && x <= max_; }
};
```### Q2: Lambda vs function object?

A: 
- Lambda: simple logic, inline definition
- Function Object: Complex logic, reuse, explicit typing```cpp
// 람다: 간단
auto isEven =  { return x % 2 == 0; };

// 함수 객체: 복잡
class Statistics {
    int count_, sum_;
public:
    void operator()(int x) { count_++; sum_ += x; }
    double average() const { return sum_ / count_; }
};
```### Q3: What is the performance of function objects?

A: Can be faster than function pointers due to inlining.```cpp
// 함수 포인터: 간접 호출
std::sort(v.begin(), v.end(), compareFunc);

// 함수 객체: 인라인 가능
std::sort(v.begin(), v.end(), CompareFunctor());
```### Q4: Can function objects be reused?

A: It is possible. You can pass the same instance to multiple algorithms.```cpp
RangeFilter filter(10, 20);

auto it1 = std::find_if(v1.begin(), v1.end(), filter);
auto it2 = std::find_if(v2.begin(), v2.end(), filter);
```### Q5: Is const required?

A: Recommended when using the STL algorithm. Function objects that do not change state must be declared as `const`.```cpp
// ✅ const 권장
struct IsEven {
    bool operator()(int x) const {
        return x % 2 == 0;
    }
};

// 상태 변경 시 mutable
class Counter {
    mutable int count_ = 0;
public:
    int operator()() const {
        return ++count_;
    }
};
```### Q6: What are standard function objects?

A: The `<functional>` header contains `std::plus`, `std::minus`, `std::greater`, etc.```cpp
#include <functional>

std::vector<int> v = {3, 1, 4, 1, 5};

// plus
int sum = std::accumulate(v.begin(), v.end(), 0, std::plus<int>());

// greater (내림차순)
std::sort(v.begin(), v.end(), std::greater<int>());
```### Q7: Can function objects be created as templates?

A: It is possible.```cpp
template<typename T>
struct Less {
    bool operator()(const T& a, const T& b) const {
        return a < b;
    }
};

std::sort(v.begin(), v.end(), Less<int>());
```### Q8: What are the function object learning resources?

A: 
- "Effective STL" by Scott Meyers (Item 38-42)
- [cppreference.com - Function objects](https://en.cppreference.com/w/cpp/utility/functional)
- "The C++ Standard Library" by Nicolai Josuttis

Related article: lambda, [bind](/blog/cpp-bind-guide/), function.

One-line summary: A function object is a class that can be called like a function by overloading `operator()`.

---

## Good article to read together (internal link)

Here's another article related to this topic.

- [C++ Function Object (Functor) Complete Guide | operator·state holding](/blog/cpp-series-46-1-function-object/)
- [C++ std::function | Callback/strategy patterns and function objects](/blog/cpp-series-13-2-function-objects/)
- [C++ Algorithm Partition | “Partition Algorithm” Guide](/blog/cpp-algorithm-partition/)

## 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++, functor, function object, operator, STL, etc.

---

## Related articles

- [C++ std::function | Callback/strategy patterns and function objects](/blog/cpp-series-13-2-function-objects/)
- [C++ Function Object (Functor) Complete Guide | operator·state holding](/blog/cpp-series-46-1-function-object/)
- [C++ ADL | ](/blog/cpp-adl-argument-dependent-lookup/)
- [C++ Algorithm Copy | ](/blog/cpp-algorithm-copy/)
- [C++ Algorithm Count | ](/blog/cpp-algorithm-count/)