C++ 함수 포인터 | "Function Pointer" 가이드

C++ 함수 포인터 | "Function Pointer" 가이드

이 글의 핵심

C++ 함수 포인터에 대해 정리한 개발 블로그 글입니다. int add(int a, int b) { return a + b; }

함수 포인터란?

함수의 주소를 저장하는 포인터

int add(int a, int b) {
    return a + b;
}

int main() {
    // 함수 포인터 선언
    int (*funcPtr)(int, int) = add;
    
    // 호출
    int result = funcPtr(3, 4);  // 7
    std::cout << result << std::endl;
}

기본 문법

// 함수 포인터 선언
int (*ptr)(int, int);

// 함수 할당
int add(int a, int b) { return a + b; }
ptr = add;
// 또는
ptr = &add;

// 호출
int result = ptr(3, 4);
// 또는
int result = (*ptr)(3, 4);

typedef/using으로 간소화

// typedef
typedef int (*Operation)(int, int);

// using (권장)
using Operation = int(*)(int, int);

int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }

int main() {
    Operation op = add;
    std::cout << op(3, 4) << std::endl;  // 7
    
    op = multiply;
    std::cout << op(3, 4) << std::endl;  // 12
}

실전 예시

예시 1: 콜백 함수

#include <vector>

void forEach(const std::vector<int>& vec, void (*callback)(int)) {
    for (int x : vec) {
        callback(x);
    }
}

void printValue(int x) {
    std::cout << x << " ";
}

void printSquare(int x) {
    std::cout << x * x << " ";
}

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    
    forEach(numbers, printValue);   // 1 2 3 4 5
    std::cout << std::endl;
    
    forEach(numbers, printSquare);  // 1 4 9 16 25
    std::cout << std::endl;
}

예시 2: 계산기

using Operation = int(*)(int, int);

int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int divide(int a, int b) { return b != 0 ? a / b : 0; }

int calculate(int a, int b, Operation op) {
    return op(a, b);
}

int main() {
    std::cout << calculate(10, 5, add) << std::endl;       // 15
    std::cout << calculate(10, 5, subtract) << std::endl;  // 5
    std::cout << calculate(10, 5, multiply) << std::endl;  // 50
    std::cout << calculate(10, 5, divide) << std::endl;    // 2
}

예시 3: 함수 테이블

#include <map>
#include <string>

using Command = void(*)();

void cmdHelp() {
    std::cout << "도움말" << std::endl;
}

void cmdQuit() {
    std::cout << "종료" << std::endl;
}

void cmdStatus() {
    std::cout << "상태 확인" << std::endl;
}

int main() {
    std::map<std::string, Command> commands = {
        {"help", cmdHelp},
        {"quit", cmdQuit},
        {"status", cmdStatus}
    };
    
    std::string input;
    while (true) {
        std::cout << "> ";
        std::cin >> input;
        
        if (input == "quit") break;
        
        auto it = commands.find(input);
        if (it != commands.end()) {
            it->second();  // 함수 호출
        } else {
            std::cout << "알 수 없는 명령" << std::endl;
        }
    }
}

예시 4: 정렬 비교 함수

#include <algorithm>
#include <vector>

bool ascending(int a, int b) {
    return a < b;
}

bool descending(int a, int b) {
    return a > b;
}

bool byAbsoluteValue(int a, int b) {
    return std::abs(a) < std::abs(b);
}

void sortVector(std::vector<int>& vec, bool (*compare)(int, int)) {
    std::sort(vec.begin(), vec.end(), compare);
}

int main() {
    std::vector<int> numbers = {-5, 2, -8, 1, 9, -3};
    
    sortVector(numbers, ascending);
    for (int x : numbers) std::cout << x << " ";
    std::cout << std::endl;  // -8 -5 -3 1 2 9
    
    sortVector(numbers, descending);
    for (int x : numbers) std::cout << x << " ";
    std::cout << std::endl;  // 9 2 1 -3 -5 -8
    
    sortVector(numbers, byAbsoluteValue);
    for (int x : numbers) std::cout << x << " ";
    std::cout << std::endl;  // 1 2 -3 -5 -8 9
}

std::function (C++11)

#include <functional>

int add(int a, int b) {
    return a + b;
}

int main() {
    // 함수 포인터
    int (*ptr)(int, int) = add;
    
    // std::function (더 유연)
    std::function<int(int, int)> func = add;
    
    // 람다도 저장 가능
    func =  { return a * b; };
    
    std::cout << func(3, 4) << std::endl;  // 12
}

멤버 함수 포인터

class Calculator {
public:
    int add(int a, int b) {
        return a + b;
    }
    
    int multiply(int a, int b) {
        return a * b;
    }
};

int main() {
    Calculator calc;
    
    // 멤버 함수 포인터
    int (Calculator::*funcPtr)(int, int) = &Calculator::add;
    
    // 호출
    int result = (calc.*funcPtr)(3, 4);  // 7
    std::cout << result << std::endl;
    
    // 포인터로 호출
    Calculator* ptr = &calc;
    result = (ptr->*funcPtr)(3, 4);
    std::cout << result << std::endl;
}

자주 발생하는 문제

문제 1: 문법 복잡성

// ❌ 복잡한 문법
int (*funcPtr)(int, int);

// ✅ using으로 간소화
using Operation = int(*)(int, int);
Operation funcPtr;

문제 2: nullptr 체크

using Callback = void(*)();

void execute(Callback cb) {
    // ❌ nullptr 체크 없음
    // cb();  // 크래시 가능
    
    // ✅ nullptr 체크
    if (cb) {
        cb();
    }
}

문제 3: 람다 캡처

int x = 10;

// ❌ 캡처하는 람다는 함수 포인터 불가
// void (*ptr)() = [x]() { std::cout << x; };  // 에러

// ✅ std::function 사용
std::function<void()> func = [x]() { std::cout << x; };

문제 4: 멤버 함수 포인터

class MyClass {
public:
    void func() {}
};

// ❌ 일반 함수 포인터로 불가
// void (*ptr)() = &MyClass::func;  // 에러

// ✅ 멤버 함수 포인터
void (MyClass::*ptr)() = &MyClass::func;

MyClass obj;
(obj.*ptr)();

함수 포인터 배열

using Operation = int(*)(int, int);

int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
int divide(int a, int b) { return b != 0 ? a / b : 0; }

int main() {
    Operation operations[] = {add, subtract, multiply, divide};
    
    for (int i = 0; i < 4; i++) {
        std::cout << operations[i](10, 5) << " ";
    }
    std::cout << std::endl;  // 15 5 50 2
}

std::function vs 함수 포인터

#include <functional>

int add(int a, int b) { return a + b; }

int main() {
    // 함수 포인터: 함수만
    int (*ptr)(int, int) = add;
    
    // std::function: 함수, 람다, 함수 객체 모두
    std::function<int(int, int)> func1 = add;
    std::function<int(int, int)> func2 =  { return a * b; };
    
    struct Multiplier {
        int operator()(int a, int b) const {
            return a * b;
        }
    };
    std::function<int(int, int)> func3 = Multiplier();
}

FAQ

Q1: 함수 포인터는 언제 사용?

A:

  • 콜백 함수
  • 함수 테이블
  • 플러그인 시스템

Q2: std::function vs 함수 포인터?

A:

  • 함수 포인터: 빠름, 함수만
  • std::function: 유연, 람다/함수 객체

Q3: 성능은?

A: 함수 포인터는 간접 호출. 약간의 오버헤드.

Q4: 멤버 함수 포인터는?

A: 다른 문법. &Class::func, (obj.*ptr)()

Q5: nullptr 체크 필요?

A: 네. 안전을 위해 체크 권장.

Q6: 함수 포인터 학습 리소스는?

A:

  • “C++ Primer”
  • cppreference.com
  • “Effective C++“

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ Observer Pointer | “관찰 포인터” 가이드
  • C++ invoke와 apply | “함수 호출” 유틸리티 가이드
  • C++ Observer Pattern 완벽 가이드 | 이벤트 기반 아키텍처와 신호/슬롯

관련 글

  • C++ 시리즈 전체 보기
  • C++ Adapter Pattern 완벽 가이드 | 인터페이스 변환과 호환성
  • C++ ADL |
  • C++ Aggregate Initialization |