C++ 표준 라이브러리에서 타입 소거(type erasure)는 다양한 타입을 동일한 인터페이스로 처리하는 핵심 기법입니다. 이는 컴파일 타임 또는 런타임에 타입 정보를 추상화하여 유연한 설계를 가능하게 하며, 특히 비동기 작업 관리 시스템 구축에 핵심적으로 활용됩니다. 본문에서는 std::function, std::variant, std::span을 중심으로 타입 소거의 실제 적용 사례를 탐구합니다.
가변 인자 처리를 위한 호출 인터페이스 통합
std::function은 다양한 호출 가능 객체(callable object)를 단일 인터페이스로 추상화합니다. 내부적으로는 추상 베이스 클래스와 템플릿 기반 파생 클래스의 조합으로 구현되며, 함수 서명(반환형, 인자 목록)을 기반으로 런타임 다형성을 지원합니다. 이 방식은 타입 정보를 런타임에 관리하므로 약간의 오버헤드가 발생하지만, 람다, 함수 포인터, 함수 객체 등을 통합적으로 처리할 수 있는 유연성을 제공합니다.
#include <iostream>
#include <functional>
#include <string>
// 문자열 처리 함수
std::string concat(const std::string& a, const std::string& b) {
return a + b;
}
// 대문자 변환 함수 객체
struct ToUpper {
std::string operator()(const std::string& s) const {
std::string result;
for (char c : s) result += std::toupper(c);
return result;
}
};
int main() {
std::function<std::string(std::string, std::string)> processor;
// 람다 표현식 할당
processor = [](const std::string& a, const std::string& b) {
return a + "-" + b;
};
std::cout << "연결: " << processor("Hello", "World") << "\n";
// 함수 객체 할당
processor = ToUpper();
std::cout << "대문자: " << processor("cpp", "erasure") << "\n";
return 0;
}
위 코드는 서로 다른 타입의 호출 가능 객체를 동일한 std::function 인터페이스로 관리하는 방식을 보여줍니다. 함수 서명이 일치하는 한 다양한 형태의 작업을 통합 처리할 수 있습니다.
데이터 저장을 위한 타입 안전 추상화
std::variant는 미리 정의된 타입 집합 내에서만 데이터를 저장하는 타입 안전한 저장소를 제공합니다. 컴파일 타임에 가능한 타입을 명시함으로써 런타임 오류를 방지하고, std::visit을 통한 일관된 처리 로직을 지원합니다. 이는 std::any의 런타임 타입 체크 오버헤드와 안전성 문제를 해결한 대안입니다.
#include <iostream>
#include <variant>
#include <string>
using DataStorage = std::variant<int, std::string, float>;
void process_data(const DataStorage& data) {
std::visit([](auto& value) {
using T = std::decay_t<decltype(value)>;
if constexpr (std::is_same_v<T, int>) {
std::cout << "정수: " << value << "\n";
} else if constexpr (std::is_same_v<T, std::string>) {
std::cout << "문자열: " << value << "\n";
} else {
std::cout << "실수: " << value << "\n";
}
}, data);
}
int main() {
DataStorage storage = 42;
process_data(storage); // 정수 출력
storage = std::string("Type Erasure");
process_data(storage); // 문자열 출력
storage = 3.14f;
process_data(storage); // 실수 출력
// 안전한 타입 체크
if (std::holds_alternative<float>(storage)) {
std::cout << "실수 값: " << std::get<float>(storage) << "\n";
}
return 0;
}
std::variant는 타입 정보를 컴파일 타임에 관리하여 런타임 오버헤드를 최소화하며, std::visit을 통해 모든 가능한 타입에 대한 처리 로직을 명시적으로 정의할 수 있습니다.
연속 메모리 접근을 위한 제로-오버헤드 추상화
std::span은 벡터, 배열 등 연속 메모리 컨테이너를 추상화하는 경량 뷰 객체입니다. 포인터와 길이 정보만으로 구성되어 런타임 오버헤드가 없으며, 다양한 컨테이너 유형에 대한 통합 접근 인터페이스를 제공합니다. 단, 비연속 메모리 구조(예: std::list)에는 적용할 수 없습니다.
#include <iostream>
#include <span>
#include <vector>
#include <array>
void display_values(std::span<const float> values) {
std::cout << "요소 수: " << values.size() << ", 값: ";
for (float v : values) std::cout << v << " ";
std::cout << "\n";
}
int main() {
std::vector<float> vec = {1.1f, 2.2f, 3.3f};
std::array<float, 4> arr = {4.4f, 5.5f, 6.6f, 7.7f};
float c_array[] = {8.8f, 9.9f};
display_values(vec); // 벡터 처리
display_values(arr); // 배열 처리
display_values(c_array); // C 스타일 배열 처리
display_values(std::span(vec).subspan(1)); // 부분 뷰 생성
return 0;
}
std::span을 사용하면 컨테이너 종류에 독립적인 알고리즘 구현이 가능하며, 부분 뷰(subspan) 생성을 통해 메모리 복사 없이도 데이터의 특정 구간을 효율적으로 처리할 수 있습니다.
비동기 작업 큐의 통합 관리
타입 소거 기법은 비동기 작업 관리 시스템에서 특히 강력합니다. std::function<void()>을 기반으로 한 작업 큐는 다양한 시그니처의 태스크를 통합 관리할 수 있습니다. 핵심은 std::packaged_task를 사용해 반환 타입을 추상화하고, std::bind로 인자 차이를 해소하는 것입니다.
#include <queue>
#include <thread>
#include <mutex>
#include <future>
#include <functional>
class AsyncExecutor {
std::queue<std::function<void()>> tasks;
std::mutex mtx;
std::condition_variable cv;
bool shutdown = false;
public:
template<typename F, typename... Args>
auto enqueue(F&& f, Args&&... args)
-> std::future<std::invoke_result_t<F, Args...>> {
using ReturnType = std::invoke_result_t<F, Args...>;
auto task = std::make_shared<std::packaged_task<ReturnType()>>(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
);
std::future<ReturnType> result = task->get_future();
{
std::lock_guard<std::mutex> lock(mtx);
tasks.emplace([task]() { (*task)(); });
}
cv.notify_one();
return result;
}
void run() {
while (true) {
std::function<void()> current_task;
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this] {
return shutdown || !tasks.empty();
});
if (shutdown && tasks.empty()) return;
current_task = std::move(tasks.front());
tasks.pop();
}
current_task();
}
}
void stop() {
{
std::lock_guard<std::mutex> lock(mtx);
shutdown = true;
}
cv.notify_all();
}
};
// 테스트 작업 정의
int compute_factorial(int n) {
int result = 1;
for (int i = 2; i <= n; ++i) result *= i;
return result;
}
std::string generate_greeting(const std::string& name) {
return "Hello, " + name;
}
int main() {
AsyncExecutor executor;
std::thread worker(&AsyncExecutor::run, &executor);
auto fut1 = executor.enqueue(compute_factorial, 5);
auto fut2 = executor.enqueue(generate_greeting, "TypeErasure");
std::cout << "5! = " << fut1.get() << "\n";
std::cout << fut2.get() << "\n";
executor.stop();
worker.join();
return 0;
}
이 구현은 서로 다른 반환 타입과 인자 목록을 가진 작업을 std::function<void()>으로 통합하여 관리합니다. std::packaged_task는 원본 작업의 반환 타입을 보존하면서도, 람다 래퍼를 통해 통합 실행 인터페이스를 제공합니다. 이는 타입 소거가 비동기 시스템 설계에서 가지는 핵심 가치를 잘 보여줍니다.