functional — 함수 객체

functional — 함수 객체 (Function objects)

**함수 객체(function object)**는 함수 호출 연산자(operator())가 정의된 모든 객체예요. C++는 내장 함수 객체를 많이 제공하고, 새로운 함수 객체를 만들고 조작하는 지원도 제공해요.

출처: cppreference

본문

함수 객체란

struct Add {
    int operator()(int a, int b) const { return a + b; }
};

Add add;
int r = add(3, 4);   // 7 — 객체를 함수처럼 호출

함수 객체는 필요한 상태를 갖고 있을 수 있어서, 함수 포인터보다 유연해요.

람다 표현식

이름 없는 함수 객체를 즉석에서 만드는 문법이에요 (C++11+).

auto mul = [](int a, int b) { return a * b; };
mul(3, 4);   // 12

표준 함수 객체 (functor)

<functional>이 제공하는 내장 함수 객체들:

  • 산술std::plus, std::minus, std::multiplies, std::divides, std::modulus, std::negate
  • 비교std::equal_to, std::not_equal_to, std::less, std::greater, std::less_equal, std::greater_equal
  • 논리std::logical_and, std::logical_or, std::logical_not
  • 비트std::bit_and, std::bit_or, std::bit_xor, std::bit_not
#include <functional>

std::plus<>{};      // 덧셈
std::less<>{};      // 비교
std::logical_and<>{};  // 논리 AND

저장·변환 도구

  • std::function — 임의의 호출 가능한 것을 시그니처로 저장하는 다형 래퍼
  • std::bind — 인자를 묶어 새 함수 객체 생성
  • std::ref/std::cref — 참조 래퍼
  • std::mem_fn — 멤버 포인터를 함수 객체로
  • std::reference_wrapper — 복사 가능한 참조

알고리즘 활용

#include <functional>
#include <algorithm>

std::sort(v.begin(), v.end(), std::greater<>{});   // 내림차순
std::transform(a.begin(), a.end(), b.begin(), std::multiplies<>{}); // 곱

함수 객체는 표준 알고리즘, 컨테이너 비교기, 콜백 등에서 범용적으로 쓰이는 개념이에요.

더 알아보기 (Learn more)

cppreference