C++ tuple apply | "튜플 적용" 가이드

C++ tuple apply | "튜플 적용" 가이드

이 글의 핵심

C++ tuple apply에 대한 실전 가이드입니다.

apply란?

std::apply 는 C++17에서 도입된 함수로, 튜플의 요소를 함수 인자로 언팩합니다. 튜플에 저장된 값들을 함수에 전달할 때 유용합니다.

#include <tuple>

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

std::tuple<int, int, int> args{1, 2, 3};

// apply: 튜플 언팩
int result = std::apply(add, args);  // add(1, 2, 3)

왜 필요한가?:

  • 튜플 언팩: 튜플을 함수 인자로 변환
  • 지연 호출: 인자를 미리 저장하고 나중에 호출
  • 메타프로그래밍: 가변 인자 처리
  • 간결성: 인덱스 기반 접근 불필요
// ❌ 인덱스 기반: 번거로움
std::tuple<int, int, int> args{1, 2, 3};
int result = add(std::get<0>(args), std::get<1>(args), std::get<2>(args));

// ✅ apply: 간결
int result = std::apply(add, args);

apply의 동작 원리:

// 개념적 구현
template<typename Func, typename Tuple, size_t... Indices>
auto apply_impl(Func&& func, Tuple&& tuple, std::index_sequence<Indices...>) {
    return func(std::get<Indices>(std::forward<Tuple>(tuple))...);
}

template<typename Func, typename Tuple>
auto apply(Func&& func, Tuple&& tuple) {
    return apply_impl(
        std::forward<Func>(func),
        std::forward<Tuple>(tuple),
        std::make_index_sequence<std::tuple_size_v<std::decay_t<Tuple>>>{}
    );
}

apply vs 직접 호출:

특징직접 호출std::apply
인자 저장❌ 불가✅ 가능
지연 호출❌ 불가✅ 가능
가변 인자❌ 어려움✅ 쉬움
성능✅ 빠름✅ 인라인 가능
// 직접 호출
int result1 = add(1, 2, 3);

// apply: 인자 저장 후 호출
auto args = std::make_tuple(1, 2, 3);
int result2 = std::apply(add, args);

기본 사용

#include <tuple>

void print(int x, double y, const std::string& z) {
    std::cout << x << ", " << y << ", " << z << std::endl;
}

int main() {
    auto args = std::make_tuple(42, 3.14, "hello");
    
    std::apply(print, args);  // print(42, 3.14, "hello")
}

실전 예시

예시 1: 람다

#include <tuple>

int main() {
    auto args = std::make_tuple(10, 20, 30);
    
    auto result = std::apply([](int a, int b, int c) {
        return a + b + c;
    }, args);
    
    std::cout << "합: " << result << std::endl;  // 60
}

예시 2: 생성자

#include <tuple>
#include <memory>

struct Widget {
    int x;
    double y;
    std::string z;
    
    Widget(int x, double y, std::string z) 
        : x(x), y(y), z(std::move(z)) {}
};

int main() {
    auto args = std::make_tuple(42, 3.14, std::string{"hello"});
    
    // apply로 생성자 인자 전달 후 make_unique
    auto widget = std::apply([](int x, double y, std::string z) {
        return std::make_unique<Widget>(x, y, std::move(z));
    }, args);
    
    std::cout << widget->x << ", " << widget->y << ", " << widget->z << std::endl;
}

예시 3: 함수 래퍼

#include <tuple>
#include <functional>

template<typename Func, typename... Args>
class DelayedCall {
    Func func;
    std::tuple<Args...> args;
    
public:
    DelayedCall(Func f, Args... a) 
        : func(f), args(std::forward<Args>(a)...) {}
    
    auto execute() {
        return std::apply(func, args);
    }
};

int main() {
    auto delayed = DelayedCall{
        [](int a, int b) { return a + b; },
        10, 20
    };
    
    std::cout << "결과: " << delayed.execute() << std::endl;  // 30
}

예시 4: 가변 인자

#include <tuple>

template<typename... Args>
void logArgs(Args&&... args) {
    auto tuple = std::make_tuple(std::forward<Args>(args)...);
    
    std::apply([](const auto&... values) {
        ((std::cout << values << " "), ...);
        std::cout << std::endl;
    }, tuple);
}

int main() {
    logArgs(1, 2.5, "hello", true);
    // 1 2.5 hello 1
}

make_from_tuple

#include <tuple>

struct Point {
    int x, y;
    Point(int x, int y) : x(x), y(y) {}
};

int main() {
    auto args = std::make_tuple(10, 20);
    
    // make_from_tuple: 생성자 호출
    auto point = std::make_from_tuple<Point>(args);
    
    std::cout << point.x << ", " << point.y << std::endl;
}

자주 발생하는 문제

문제 1: 참조

int x = 42;
auto args = std::make_tuple(x);  // 복사

// ✅ 참조
auto args2 = std::forward_as_tuple(x);  // 참조

std::apply([](int& val) {
    val = 100;
}, args2);

std::cout << x << std::endl;  // 100

문제 2: 인자 개수

void func(int a, int b) {
    std::cout << a + b << std::endl;
}

// ❌ 인자 개수 불일치
// auto args = std::make_tuple(1, 2, 3);
// std::apply(func, args);  // 에러

// ✅ 정확한 개수
auto args = std::make_tuple(1, 2);
std::apply(func, args);

문제 3: 타입 추론

// auto: 복잡한 타입
auto t = std::make_tuple(42, 3.14);

// 명시적 타입
std::tuple<int, double> t2{42, 3.14};

문제 4: 성능

// apply는 인라인 가능
// 오버헤드 최소화

// 하지만 튜플 생성 비용
auto args = std::make_tuple(1, 2, 3);  // 복사
std::apply(func, args);

// ✅ 직접 호출 (가능한 경우)
func(1, 2, 3);

활용 패턴

// 1. 여러 값 반환
std::tuple<int, std::string> parse();

// 2. 함수 인자 저장
auto args = std::make_tuple(1, 2, 3);
std::apply(func, args);

// 3. 생성자 호출
auto obj = std::make_from_tuple<T>(args);

// 4. 가변 인자 처리
template<typename... Args>
void process(Args&&... args);

실무 패턴

패턴 1: 비동기 작업

#include <tuple>
#include <future>

template<typename Func, typename... Args>
auto asyncApply(Func&& func, std::tuple<Args...> args) {
    return std::async(std::launch::async, [func = std::forward<Func>(func), args = std::move(args)]() {
        return std::apply(func, args);
    });
}

// 사용
int compute(int a, int b, int c) {
    return a * b + c;
}

auto args = std::make_tuple(10, 20, 5);
auto future = asyncApply(compute, args);
std::cout << "결과: " << future.get() << '\n';  // 205

패턴 2: 함수 캐시

인자 묶음을 키로 쓸 때 std::tuple + std::apply가변 인자 함수를 균일하게 호출할 수 있습니다.

#include <map>
#include <tuple>
#include <functional>

template<typename Func>
class MemoizedBinary {
    Func func_;
    std::map<std::pair<int, int>, int> cache_;

public:
    explicit MemoizedBinary(Func f) : func_(std::move(f)) {}

    int operator()(int a, int b) {
        auto key = std::make_pair(a, b);
        if (auto it = cache_.find(key); it != cache_.end()) {
            return it->second;
        }
        auto tup = std::make_tuple(a, b);
        int result = std::apply(func_, tup);
        cache_.emplace(key, result);
        return result;
    }
};

// 사용
auto add_cached = MemoizedBinary([](int a, int b) { return a + b; });

패턴 3: 배치 처리

template<typename Func>
class BatchProcessor {
    Func func_;
    std::vector<std::tuple<int, int>> batch_;
    
public:
    BatchProcessor(Func func) : func_(func) {}
    
    void add(int a, int b) {
        batch_.emplace_back(a, b);
    }
    
    void process() {
        for (auto& args : batch_) {
            auto result = std::apply(func_, args);
            std::cout << "결과: " << result << '\n';
        }
        batch_.clear();
    }
};

// 사용
BatchProcessor processor([](int a, int b) {
    return a + b;
});

processor.add(1, 2);
processor.add(3, 4);
processor.process();
// 결과: 3
// 결과: 7

std::apply 활용 심화

  • std::invoke와 조합: 멤버 포인터나 optional에 담긴 함수를 호출할 때는 먼저 std::invoke를 떠올리고, 인자 묶음이 튜플이면 std::apply로 풀어 줍니다. apply의 첫 인자는 호출 가능 객체라서 람다·함수 객체·바인딩 결과가 그대로 들어갑니다.
  • 반환형: decltype(auto)std::invoke_result_t반환 타입을 추론해, 템플릿 API에서 “튜플을 넣으면 함수 시그니처와 맞는지” 컴파일 타임에 검증됩니다.
  • const 튜플: std::apply(f, std::as_const(t))처럼 읽기 전용 튜플을 넘기면, 요소가 참조일 때 수정 가능 여부가 명확해집니다.

함수 인자 언팩: 튜플 vs 매개변수 팩

방식언제 쓰나메모
매개변수 팩 (...)템플릿 가변 인자 직접 전달std::forward와 함께 완벽 전달 관용구
튜플 + apply런타임에 묶음이 정해지거나, 한 값으로 저장·이동해야 할 때인자 개수는 고정이어야 컴파일됨
make_from_tuple생성자에 튜플 내용을 그대로 대응시킬 때explicit 생성자도 호출 가능

가변 인자 템플릿으로 이미 (args...)를 갖고 있다면 굳이 tuple로 만들 필요는 없고, 지연 실행·큐·직렬화처럼 “나중에 한 번에 호출”해야 할 때 tuple + apply가 빛을 냅니다.

실전 패턴 보강

  • 설정/CLI 파싱: 키-값을 tuple로 묶어 두고, 검증 함수 bool validate(T...)apply로 넘기면 인자 순서를 한 곳에서 관리하기 쉽습니다.
  • SQL 바인딩·RPC 스텁: 컬럼/필드 타입이 튜플로 고정된 경우, apply프로시저 호출을 포장할 수 있습니다(실제로는 DB API가 튜플을 지원하지 않으므로, 내부에서 apply로 풀어 bind 호출을 생성하는 식).
  • 테스트 픽스처: std::tuple로 입력 케이스를 표현하고 apply테스트 대상 함수를 호출하면, 데이터 주도 테스트가 간결해집니다.

메타프로그래밍과의 연결

std::apply의 구현은 전형적으로 std::index_sequencestd::get<I>접근을 사용합니다. 즉, 컴파일 타임에 길이가 정해진 튜플에 대해, 런타임 오버헤드 없이 펼침 호출을 합니다.

// 개념: index_sequence로 0..N-1 에 대해 std::get<I>(t)...
template<class F, class Tuple, std::size_t... I>
constexpr decltype(auto) apply_impl(F&& f, Tuple&& t, std::index_sequence<I...>) {
    return std::invoke(std::forward<F>(f), std::get<I>(std::forward<Tuple>(t))...);
}

C++23 std::bind_front / std::invoke_r 등과 함께 쓰면, 부분 적용된 함수에 나머지 인자만 튜플로 넘기는 패턴도 정리하기 쉽습니다. 메타프로그래밍 관점에서 apply“튜플 타입을 함수 시그니처로 변환하는 접착제”로 기억하면 좋습니다.

FAQ

Q1: tuple은 무엇인가요?

A: C++11의 여러 값을 묶는 컨테이너입니다. 서로 다른 타입을 저장할 수 있습니다.

std::tuple<int, double, std::string> t{42, 3.14, "hello"};

auto [x, y, z] = t;  // C++17 structured binding

Q2: apply는 무엇인가요?

A: C++17의 튜플을 함수 인자로 언팩하는 함수입니다.

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

auto args = std::make_tuple(2, 3);
int result = std::apply(add, args);  // add(2, 3)

Q3: 튜플 언팩 방법은?

A:

  • structured binding (C++17): auto [x, y, z] = tuple;
  • tie: std::tie(x, y, z) = tuple;
  • apply: std::apply(func, tuple);
std::tuple<int, double, std::string> t{42, 3.14, "hello"};

// structured binding
auto [x, y, z] = t;

// tie
int a;
double b;
std::string c;
std::tie(a, b, c) = t;

// apply
std::apply([](int x, double y, const std::string& z) {
    std::cout << x << ", " << y << ", " << z << '\n';
}, t);

Q4: 참조는 어떻게 저장하나요?

A: std::forward_as_tuple 을 사용합니다.

int x = 42;

// make_tuple: 복사
auto t1 = std::make_tuple(x);

// forward_as_tuple: 참조
auto t2 = std::forward_as_tuple(x);

std::apply([](int& val) {
    val = 100;
}, t2);

std::cout << x << '\n';  // 100

Q5: apply의 성능은?

A: 인라인 가능하여 오버헤드가 최소화됩니다.

// 컴파일러가 인라인 최적화
std::apply(add, std::make_tuple(1, 2, 3));
// → add(1, 2, 3) (직접 호출과 동일)

Q6: make_from_tuple은 무엇인가요?

A: 튜플을 생성자 인자로 사용하여 객체를 생성합니다.

struct Point {
    int x, y;
    Point(int x, int y) : x(x), y(y) {}
};

auto args = std::make_tuple(10, 20);
auto point = std::make_from_tuple<Point>(args);  // Point(10, 20)

Q7: 빈 튜플은 어떻게 처리하나요?

A: 빈 튜플도 가능합니다. 인자 없는 함수에 사용합니다.

void func() {
    std::cout << "인자 없음\n";
}

std::tuple<> empty;
std::apply(func, empty);  // func()

Q8: tuple apply 학습 리소스는?

A:

관련 글: tuple, structured-binding, variadic-templates.

한 줄 요약: std::apply는 튜플의 요소를 함수 인자로 언팩하는 C++17 함수입니다.


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

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

  • C++ invoke와 apply | “함수 호출” 유틸리티 가이드
  • C++ Structured Binding | “구조적 바인딩” C++17 가이드
  • C++ Copy Elision | “복사 생략” 가이드

관련 글

  • C++ invoke와 apply |
  • C++ any |
  • 모던 C++ (C++11~C++20) 핵심 문법 치트시트 | 현업에서 자주 쓰는 한눈에 보기
  • C++ CTAD |
  • C++ string vs string_view |