Cheat Sheet - Linux: /kr/linux/ - CLI: /kr/linux/cli/ - locate vs type vs which vs whereis: /kr/linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /kr/linux/cli/make/ - awk: /kr/linux/cli/awk/ - find: /kr/linux/cli/find/ - grep: /kr/linux/cli/grep/ - pgrep: /kr/linux/cli/pgrep/ - ps: /kr/linux/cli/ps/ - pstree: /kr/linux/cli/pstree/ - trap: /kr/linux/cli/trap/ - xargs: /kr/linux/cli/xargs/ - Shell: /kr/linux/shell/ - BASH_SOURCE: /kr/linux/shell/bash-source/ - Redirection: /kr/linux/shell/redirection/ - Special Variables: /kr/linux/shell/special-variables/ - Interactive Shell과 Login Shell의 정의: /kr/linux/shell/interactive-login/ - Scripting Tips: /kr/linux/shell/script-tips/ - set -o vi: /kr/linux/shell/bash-vi-mode/ - Shell 실행 순서: /kr/linux/shell/process-order/ - Double Quote Expansion: /kr/linux/shell/shell-expansion/ - System Programming: /kr/linux/system-programming/ - File I/O: /kr/linux/system-programming/file-io/ - Process: /kr/linux/system-programming/process/ - Shared Libraries: /kr/linux/system-programming/shared-libraries/ - Kernel: /kr/linux/kernel/ - Go: /kr/programming/go/ - Concurrency: /kr/programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /kr/programming/go/concurrency/csp/ - Channel: /kr/programming/go/concurrency/channel/ - Select: /kr/programming/go/concurrency/select/ - sync: /kr/programming/go/concurrency/sync/ - Concurrency Patterns: /kr/programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /kr/programming/go/concurrency/runtime/ - 표준 라이브러리: /kr/programming/go/std/ - os: /kr/programming/go/std/os/ - context: /kr/programming/go/std/context/ - io: /kr/programming/go/std/io/ - json: /kr/programming/go/std/json/ - net/http: /kr/programming/go/std/net-http/ - slog: /kr/programming/go/std/slog/ - testing: /kr/programming/go/std/testing/ - time: /kr/programming/go/std/time/ - Ellipsis (...): /kr/programming/go/ellipsis/ - error: /kr/programming/go/error/ - Function: /kr/programming/go/function/ - Go Tool: /kr/programming/go/tool/ - Interface: /kr/programming/go/interface/ - Map: /kr/programming/go/map/ - Package and Module: /kr/programming/go/package-module/ - Pointer: /kr/programming/go/pointer/ - Slice: /kr/programming/go/slice/ - String: /kr/programming/go/string/ - Switch: /kr/programming/go/switch/ - Comparison: /kr/programming/go/comparison/ - defaultdict: /kr/programming/python/collections/defaultdict/ - heapq: /kr/programming/python/collections/heapq/ - @cache: /kr/programming/python/cache/ - abc: /kr/programming/python/abc/ - bisect: /kr/programming/python/bisect/ - Type Hints: /kr/programming/python/type-hints/ - Passing Mechanism: /kr/programming/python/passing-mechanism/ - uv: /kr/programming/python/uv/ - *args and **kwargs: /kr/programming/python/args-kwargs/ - re: /kr/programming/python/re/ - C: /kr/programming/c/ - 포인터와 배열: /kr/programming/c/pointer/ - Syntax Basics: /kr/programming/c/syntax-basics/ - static: /kr/programming/c/static/ - Bit Manipulation: /kr/programming/c/bit-manipulation/ - C vs C++: /kr/programming/c/c-vs-cpp/ - stdatomic: /kr/programming/c/stdatomic/ - C++: /kr/programming/cpp/ - RAII (Resource Acquisition Is Initialization): /kr/programming/cpp/raii/ - Copy Elision & Move Semantics: /kr/programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /kr/programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /kr/programming/cpp/keywords/ - C++ Primer: /kr/programming/cpp/primer/ - Variables and Basic Types: /kr/programming/cpp/primer/variables-and-basic-types/ - Expressions: /kr/programming/cpp/primer/expressions/ - Type Conversions and Casts: /kr/programming/cpp/primer/type-conversions-and-casts/ - Statements: /kr/programming/cpp/primer/statements/ - Functions: /kr/programming/cpp/primer/functions/ - Classes: /kr/programming/cpp/primer/classes/ - The IO Library: /kr/programming/cpp/primer/io-library/ - STL: /kr/programming/cpp/primer/stl/ - Lambda Expressions: /kr/programming/cpp/primer/lambda/ - Smart Pointers: /kr/programming/cpp/primer/smart-pointers/ - Copy Control: /kr/programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /kr/programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /kr/programming/cpp/primer/oop/ - Templates and Generic Programming: /kr/programming/cpp/primer/templates/ - Namespaces: /kr/programming/cpp/primer/namespaces/ - Pointers to Class Member: /kr/programming/cpp/primer/pointers-to-class-member/ - Advanced: /kr/programming/cpp/advanced/ - Error Handling: /kr/programming/cpp/advanced/error-handling/ - Concurrency & Threading: /kr/programming/cpp/advanced/concurrency/ - Unit Testing: /kr/programming/cpp/advanced/unit-testing/ - 언어 별 비교: /kr/programming/comparison/ - Kubernetes: /kr/cloud-devops/kubernetes/ - Fleet: /kr/cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /kr/cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /kr/cloud-devops/kubernetes/api-extension/ - Concept: /kr/cloud-devops/kubernetes/kueue/concept/ - DRA: /kr/cloud-devops/kubernetes/dra/ - Secret Manager: /kr/cloud-devops/terraform/google-secret-manager/ - Knowledge: /kr/network/knowledge/ - PDU: /kr/network/knowledge/osi-model/ - curl: /kr/network/cli/curl/ - Concurrency Concepts: /kr/cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /kr/cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /kr/cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /kr/cs/regular-expression/ - Multiplexer vs Dispatcher: /kr/cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /kr/ai-ml/gpu/driver-and-runtime/ - Serving: /kr/ai-ml/serving/ - Dotfiles: /kr/dotfiles/ - Git: /kr/dotfiles/git/ - Cheat Sheet: /kr/dotfiles/git/cheat-sheet/ - revisions: /kr/dotfiles/git/revisions/ - Submodule vs Worktree: /kr/dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /kr/dotfiles/git/checkout-switch-restore-reset/ - rebase: /kr/dotfiles/git/rebase/ - Branching and Merging: /kr/dotfiles/git/branching-merging/ - Vim: /kr/dotfiles/vim/ - Plugin: /kr/dotfiles/vim/plugin/ - auto-pairs: /kr/dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /kr/dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /kr/dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /kr/dotfiles/vim/plugin/vim-surround/ - Marks: /kr/dotfiles/vim/tips/marks/ - vimrc: /kr/dotfiles/vim/vimrc/ - lf: /kr/dotfiles/lf/ # Templates and Generic Programming {{< katex />}} *C++ Primer, 5th ed.* 16장 Templates and Generic Programming을 바탕으로 function / class template의 instantiation 원리, **Template Argument Deduction**, **Forwarding Reference** (`T&&`) 및 **Reference Collapsing**, **Variadic Templates** (`Args...`)와 `emplace_back`의 내부 원리, 그리고 **Template Specialization**을 정리한다. ## 1. Function Template과 Class Template의 기본 원리 - **Template Instantiation:** template 자체는 실행 코드가 아니라 컴파일러를 위한 **blueprint**다. 개발자가 `compare(1, 0)`이나 `std::vector`처럼 template을 사용하는 순간, 컴파일러가 type parameter `T`에 실제 타입을 대입해 구체적인 함수나 class를 생성한다. - **왜 template의 선언과 정의는 모두 헤더 파일(`.h`)에 있어야 하는가?** - 일반 함수는 선언만 보고도 호출 코드를 컴파일한 뒤 링커가 `.o` 목적 파일을 연결할 수 있지만, **template은 컴파일러가 구체적인 타입으로 코드를 직접 인스턴스화해야 하므로 호출하는 소스 파일에서 template의 전체 본문 코드를 반드시 볼 수 있어야 한다.** ### 1. Type Parameter(`typename` / `class`)와 Non-type Parameter Template parameter로는 type parameter(`typename T`)뿐만 아니라 정수, 포인터, 참조 등 **컴파일 타임 상수 값**을 받는 **Non-type Template Parameter**도 사용할 수 있다: ```cpp // 1. Type Template Parameter (typename과 class는 완전히 동일한 의미) template int compare(const T &v1, const T &v2) { if (v1 < v2) return -1; if (v2 < v1) return 1; return 0; } // 2. Non-type Template Parameter (unsigned N, unsigned M): // 배열의 참조를 받아 길이가 다른 문자열 리터럴을 pointer decay 없이 그대로 바인딩 template int compare(const char (&p1)[N], const char (&p2)[M]) { return strcmp(p1, p2); } int r = compare("hi", "mom"); // 호출 시 컴파일러가 N을 3, M을 4로 자동 추론해 compare<3, 4> 인스턴스화 ``` ### 2. Dependent Type Name과 `typename` 키워드 필수 규칙 Type parameter `T`에 의존하는 중첩 이름인 `T::Bar` 등에 접근할 때, 컴파일러는 `T`가 인스턴스화되기 전까지 그 이름이 **중첩 타입**인지 **`static` member 변수·함수나 열거자 등 타입이 아닌 member**인지 알 수 없다. 예를 들어 아래의 `T::Bar * x;` 한 줄은 `T`에 무엇이 들어오느냐에 따라 문법 구조 자체가 달라진다: ```cpp int x = 10; template void func() { T::Bar * x; // 포인터 변수 선언문인가, 곱셈 수식인가? } ``` - `struct A { using Bar = int; };`가 들어오면 (`Bar`가 중첩 타입): `int * x;`가 되어 포인터 변수 `x`를 새로 만드는 **변수 선언문**이 된다 (`*`는 포인터 기호). - `struct B { static int Bar; };`가 들어오면 (`Bar`가 `static` 변수): 정적 변수 `B::Bar`와 변수 `x`를 곱하는 **곱셈 수식**이 된다 (`*`는 곱하기 연산자). 이 모호성을 없애기 위해 C++은 앞에 아무 표시가 없는 `T::...`를 기본적으로 **타입이 아닌 이름**으로 간주한다. 따라서 `T::...`가 **타입**임을 컴파일러에게 알려주려면 반드시 앞에 `typename`을 붙여야 하며, 이 자리에서는 `class`로 대체할 수 없다: ```cpp template // Container::value_type과 Container::const_iterator가 타입임을 명시하기 위해 typename 필수 typename Container::value_type top_element(const Container &c) { typename Container::const_iterator it = c.begin(); return *it; } ``` --- ## 2. Template Argument Deduction과 Reference Collapsing Template으로 정의된 함수나 class(C++17 CTAD 이후)를 사용할 때 **``로 타입 인자를 직접 명시하지 않고 전달된 인자만으로 컴파일러에게 `T` 추론을 맡기는 과정**을 **Template Argument Deduction**이라 한다. 예를 들어 `compare(1, 0)` 대신 `compare(1, 0)`으로 호출할 때, function template의 매개변수 선언 형태(`T`, `T&` / `const T&`, `T&&`)에 따라 `T` 추론 규칙이 다음 세 가지로 나뉜다: | Function Template의 매개변수 형태 | `const` 보존 여부 | 배열/함수 Decay 여부 | 핵심 특징 | | :--- | :--- | :--- | :--- | | **값 전달 (`T`)** | Top-level `const` 제거됨 | 배열/함수가 포인터(`T*`)로 pointer decay됨 | [객체 복사 시의 규칙]({{< relref "/programming/cpp/primer/variables-and-basic-types.kr.md#객체-복사-시의-규칙" >}})과 동일하게 새 복사본이 생성되므로 원본의 top-level `const`가 무시된다. | | **참조 전달 (`T&` / `const T&`)** | Low-level `const` 보존됨 | pointer decay 없이 배열 참조(`T (&)[N]`)로 유지됨 | 예: `compare(const T&, const T&)`에 길이가 다른 두 문자열 리터럴(`"hi"`, `"world"`)을 넘기면 `T`가 각각 `char[3]`과 `char[6]`으로 다르게 추론되어 컴파일 에러가 난다. | | **Forwarding Reference (`T&&`)** | 인자의 value category와 `const` 모두 보존 | lvalue 배열/함수는 pointer decay 없이 참조로 유지됨 | 아래의 특별 lvalue 추론 규칙과 Reference Collapsing을 통해 lvalue와 rvalue를 모두 원형 그대로 받을 수 있다. | ### Forwarding Reference(`T&&`)와 Reference Collapsing 규칙 [`make_unique`]({{< relref "/programming/cpp/primer/smart-pointers.kr.md#2-stdunique_ptr-독점-소유권과-stdmake_unique" >}})나 `emplace_back` 같이 parameter를 받아 다른 함수로 전달하는 template wrapper 함수는 인자의 constness와 value category를 **복사 비용 없이 원형 그대로** 넘겨주어야 한다. 다른 매개변수 형태로는 이 조건을 만족할 수 없다: | Function Template의 매개변수 선언 | Perfect Forwarding에 실패하는 이유 | | :--- | :--- | | **`T arg`** | 받는 순간 값 복사본이 생성되어 복사 비용이 들고 원본 참조를 전달할 수 없음 | | **`T& arg`** | `42`, `"hello"` 같은 rvalue를 바인딩할 수 없어 컴파일 에러 발생 | | **`const T& arg`** | lvalue·rvalue 모두 받을 수는 있지만 무조건 `const`가 붙어 template 함수 안에서 non-`const` 참조 전달이 막히고, rvalue를 넘겨도 move constructor 대신 비싼 copy constructor가 호출됨 | lvalue와 rvalue를 모두 고려하기 위해 인자마다 `const T&`와 `T&&`를 일일이 오버로딩하면 인자가 $N$개일 때 $2^N$개의 함수가 필요해진다. 이를 단 하나의 function template으로 해결하는 문법이 **type parameter `T`에 직접 붙은 `T&&`**, 즉 **Forwarding Reference**다: 1. **Forwarding Reference `T&&`의 특별 lvalue 추론 규칙 (`[temp.deduct.call]`):** - 만약 일반 template 추론처럼 `int` 타입의 lvalue 인자에 대해서도 `T`를 `int`로 추론해 버리면, 매개변수 타입이 `int&&`가 되어 lvalue를 바인딩할 수 없으므로 컴파일 에러가 난다. - 이를 해결하기 위해 C++11 표준은 "function template의 추론 대상 매개변수가 정확히 `T&&` 형태일 때, rvalue를 넘기면 `T`를 값 타입 `int`로 추론하고 lvalue를 넘기면 `T`를 lvalue 참조 타입 `int&`로 추론한다"는 특별 예외 규칙을 도입했다. - **발동 조건 주의:** 해당 function template 자체의 추론 대상 `T`에 아무 수식 없이 정확히 `T&&` 형태일 때만 작동한다. `const T&&`, `std::vector&&`처럼 `const`나 컨테이너가 붙거나 class template의 생성자 매개변수인 경우에는 특별 규칙이 적용되지 않고 일반 rvalue 참조로 동작한다. 2. **Reference Collapsing 규칙:** - `T`가 `int&`로 추론되면 매개변수 타입은 `int& &&` 형태가 되며, 컴파일러는 다음 규칙으로 축약한다: - **`T& &`, `T& &&`, `T&& &` → 모두 `T&`로 축약:** lvalue 참조 `&`가 하나라도 섞이면 무조건 `&`가 된다. - **`T&& &&` → 오직 이 경우에만 `T&&`로 축약:** 둘 다 rvalue 참조일 때만 `&&`가 유지된다. | 호출 인자 (`int` 기준) | 추론된 `T` 타입 | 축약 전 `T&&` | Reference Collapsing 후 최종 매개변수 타입 | `std::forward(ARG)` 결과 | | :--- | :--- | :--- | :--- | :--- | | **non-`const` lvalue** | `int&` | `int& &&` | **`int&`** | `int&`로 복원되어 non-`const` lvalue 유지 | | **`const` lvalue** | `const int&` | `const int& &&` | **`const int&`** | `const int&`로 복원되어 `const` lvalue 유지 | | **rvalue (`42`)** | `int` | `int &&` | **`int&&`** | `int&&`로 복원되어 rvalue 유지 | 함수 안으로 들어온 매개변수 `ARG`는 이름이 있는 변수이므로 본문에서 이름만 쓰면 무조건 lvalue로 평가되지만, 추론된 `T`가 참조 타입 `int&`인지 값 타입 `int`인지에 따라 원래 인자가 lvalue였는지 rvalue였는지 기록이 그대로 남아 있다. `std::forward(ARG)`는 바로 이 `T`의 기록을 보고 원래 value category를 복원하여 **Perfect Forwarding**을 완성한다. 코드 예시는 [Copy Elision & Move Semantics: `std::move` vs. `std::forward`]({{< relref "/programming/cpp/copy-elision-and-move-semantics.kr.md#2-stdmove-vs-stdforward-move-semantics-vs-perfect-forwarding" >}}) 참조. --- ## 3. Variadic Templates (`Args...`)와 `emplace_back` **Variadic Template**은 0개 이상의 임의 개수의 타입과 인자를 받을 수 있는 template이다. `...`의 위치에 따라 **이름 앞에 오면 '묶기'**, 식 맨 뒤에 오면 '펼치기'로 동작한다: - **이름 앞의 `...` — Parameter Pack 선언:** - **Template Parameter Pack (`typename... Args`):** 0개 이상의 타입 목록을 `Args` 하나로 묶는다. - **Function Parameter Pack (`Args&&... args`):** 0개 이상의 함수 인자 목록을 `args` 하나로 묶는다. 이름에 Function이 들어가지만 일반 함수에서는 쓸 수 없고, 앞서 선언된 Template Parameter Pack을 받는 template 함수(또는 variadic class template의 member 함수)에서만 사용할 수 있다. - **식 맨 뒤의 `...` — Pack Expansion:** - **`PATTERN...`:** `...` 바로 왼쪽에 있는 **패턴 전체**를 원소 개수만큼 복제하여 쉼표 `,`로 나열한다. - 예: `args...`는 `arg1, arg2`로 펼쳐지고, `std::forward(args)...`는 `std::forward(arg1), std::forward(arg2)`로 펼쳐진다. 만약 닫는 괄호 안쪽에 `std::forward(args...)`라고 쓰면 단일 `std::forward` 함수에 인자 여러 개를 한꺼번에 넣는 `std::forward(arg1, arg2)`가 되어 컴파일 에러가 발생한다. - **`sizeof...(Args)` 연산자:** pack 안에 들어있는 타입·인자의 개수를 컴파일 타임에 반환한다. ### 1. Variadic Template 재귀 패턴 Variadic 함수는 보통 첫 번째 인자를 처리한 뒤 나머지 pack을 재귀적으로 넘기며, **재귀를 멈추기 위한 non-variadic base case 함수가 반드시 variadic 버전보다 먼저 선언되어 있어야 한다**: ```cpp #include // 1. Base Case (반드시 먼저 선언): 마지막 남은 1개의 인자를 출력하고 재귀를 종료함 template std::ostream& print(std::ostream &os, const T &t) { return os << t; } // 2. Variadic Function Template: 첫 번째 인자 t를 출력하고 나머지 rest...를 재귀 호출 (Pack Expansion) template std::ostream& print(std::ostream &os, const T &t, const Args&... rest) { os << t << ", "; return print(os, rest...); // rest...가 풀리면서 인자가 하나씩 줄어듦 } ``` ### 2. Pack Expansion과 `emplace_back`의 내부 원리 표준 컨테이너의 `emplace_back`이나 `std::make_unique`가 임시 객체를 만들지 않고 대상 메모리에서 직접 원소 생성자를 호출할 수 있는 비결은 Variadic Forwarding Reference(`Args&&...`)와 **`std::forward(args)...` Pack Expansion**의 조합이다: ```cpp template class Vec { public: // Args&&...로 임의 개수의 생성자 인자를 묶어 받고, std::forward(args)...로 패턴 통째로 펼쳐 전달 template void emplace_back(Args&&... args) { chk_n_alloc(); // 남은 버퍼 용량을 확인하고 필요 시 재할당 alloc.construct(first_free++, std::forward(args)...); } }; // 예: vec.emplace_back(10, 'c') 호출 시 컴파일러가 ...을 풀어서 생성하는 실제 코드 (Args가 int, char로 추론됨) // void emplace_back(int&& arg1, char&& arg2) { // chk_n_alloc(); // alloc.construct(first_free++, std::forward(arg1), std::forward(arg2)); // } ``` --- ## 4. Template Specialization Primary Template 코드가 특정 타입이나 타입 패턴에 대해 잘못 동작하거나 비효율적일 때, 해당 경우만을 위한 전용 구현을 별도로 정의하는 것을 **Template Specialization**이라고 한다. ### 1. 왜 Full Specialization에서는 `template <>`처럼 빈 꺾쇠괄호를 쓰는가? - **Primary Template (`template `):** 아직 정해지지 않은 미지수 type parameter `T`가 1개 남아있다는 뜻이다. - **Explicit Full Specialization (`template <>`):** 미지수였던 `T` 자리에 `std::string`이나 `int` 같은 구체적인 타입을 모두 대입해 확정 지었으므로, "남아있는 미지수 type parameter가 0개여서 `<>` 안이 비어 있다"고 컴파일러에게 알려주는 표식이다. `template <>`를 생략하고 함수 이름에만 `` 등을 붙이면 문법 에러가 발생한다. ```cpp // 1. Primary Template: 임의의 타입 C를 스트림에 넣어 문자열로 변환 template inline std::string Stringify(const C &value) { std::ostringstream o; o << value; return o.str(); } // 2. Explicit Full Specialization: // C를 std::string으로 확정했으므로 미지수 parameter가 0개 남음 -> template <> template <> inline std::string Stringify(const std::string &s) { // 은 인자 추론이 가능하면 생략 가능 return "\"" + s + "\""; // 문자열일 때만 양옆에 큰따옴표를 붙임 } ``` ### 2. Full Specialization vs. Partial Specialization 남아있는 미지수 template parameter가 있는지 여부에 따라 두 가지로 나뉜다: - **Full Specialization (`template <>`):** Primary Template의 **모든 template parameter를 구체적인 타입이나 상수로 완전히 확정**하여 남은 미지수가 0개인 특수화다. 예컨대 `struct hash`나 `struct Map`처럼 대상 타입이 단 하나로 정해진다. - **Partial Specialization (`template <...>`):** 모든 parameter를 확정 짓지 않고 **일부 미지수를 남겨둔 채 범위만 좁혀 특수화**하는 방식이다. 미지수가 남아 있으므로 `template <>`가 아니라 여전히 `template <...>` 안에 남은 미지수를 적으며, 크게 두 가지 형태가 있다: 1. **여러 parameter 중 일부만 고정:** `template struct Map`에서 `K`만 `std::string`으로 확정하고 `V`는 미지수로 남겨두는 `template struct Map` 2. **타입 패턴만 제한:** 특정 타입 하나로 확정하지 않고 모든 포인터(`T*`), 참조(`T&`, `T&&`), 배열(`T[N]`)처럼 타입의 형태만 제한하는 `template struct hash` Function template과 class template에서의 지원 여부는 다음과 같다: | 구분 | Function Template (`template void f(T)`) | Class / Struct Template (`template struct Foo`) | | :--- | :--- | :--- | | **Full Specialization** | ✅ `template <> int compare(const char* const &p1, const char* const &p2)` | ✅ `template <> struct hash` | | **Partial Specialization** | ❌ Function template은 **함수 오버로딩**으로 대체함 | ✅ 일부 parameter 고정 및 `T*`, `T&`, `T[N]` 패턴 특수화 모두 지원 | - **왜 Primary Template `struct hash` 하나로 처리하거나 이름만 같은 `struct hash`를 하나 더 만들 수 없는가?** 1. 일반 객체 타입(`T`), 포인터 타입(`T*`), 배열 타입(`T[N]`)은 해시 계산 방식이 완전히 다르므로 하나의 Primary Template에 넣을 수 없다. 예를 들어 포인터는 주소를 `reinterpret_cast`로 변환하지만 일반 객체에는 불가능하다. 2. `class`와 `struct`는 함수와 달리 **오버로딩이 불가능**하다. 이름 뒤에 `` 없이 `template struct hash`를 또 정의하면 재정의 에러(`redefinition of 'hash'`)가 발생하므로, **`struct hash`처럼 패턴을 명시해 분기**해야 한다. - **Partial Specialization은 Primary Template보다 type / non-type parameter 개수가 더 늘어날 수도 있다:** - Primary Template `template struct hash`는 parameter가 `T` 1개뿐이지만, 고정 크기 배열 패턴 `T[N]`을 Partial Specialization하려면 원소 타입 `T`와 배열 길이 `N` 2개가 필요하므로 `template struct hash`처럼 parameter가 늘어난다. - **컴파일러의 매칭 우선순위:** **1순위 Full Specialization (`hash`) $\rightarrow$ 2순위 Partial Specialization (`hash`, `hash`) $\rightarrow$ 3순위 Primary Template (`hash`)** 순으로 가장 구체적인 구현이 선택된다. ```cpp // Primary Template + Full Specialization + Partial Specialization (T*, T[N]) 전체 구조 // [1] Primary Template (나머지 일반 타입 T) template struct hash { size_t operator()(const T &x) const { return x.CustomHash(); } }; // [2] Full Specialization (T를 int64_t 하나로 확정 -> 남은 미지수 0개이므로 template <>) template <> struct hash { size_t operator()(int64_t x) const { return static_cast(x); } }; // [3] Partial Specialization #1: 모든 포인터 타입 (T* 패턴 -> 가리키는 타입 T가 미지수이므로 template ) template struct hash { size_t operator()(T *x) const { return reinterpret_cast(x); } }; // [4] Partial Specialization #2: 모든 배열 타입 (T[N] 패턴 -> parameter가 T, N 2개로 늘어남) template struct hash { size_t operator()(const T (&arr)[N]) const { size_t total = 0; hash elem_hasher; for (size_t i = 0; i < N; ++i) total ^= elem_hasher(arr[i]); return total; } }; ``` ### 3. Function Template Specialization(`template <>`) vs. 일반 함수 오버로딩 함수에 특정 타입 예외 처리를 할 때는 **`template <>` Explicit Specialization**과 **`template <>` 없는 일반 함수 오버로딩** 두 가지 방법이 있다. 예를 들어 C 문자열(`const char*`)일 때 양옆에 큰따옴표를 붙이려는 상황을 비교해 보자: ```cpp // 기본 Primary Template: 임의의 타입 C를 스트림에 넣어 문자열로 변환 template std::string Stringify(const C &value) { std::ostringstream o; o << value; return o.str(); } // 방법 1: template <> Explicit Specialization (위 Primary Template에 종속된 특수화 구현) template <> std::string Stringify(const char* const &s) { // const C&의 C 자리에 const char*를 대입한 시그니처 return "\"" + std::string(s) + "\""; } // 방법 2: 일반 함수 오버로딩 (template <> 없이 별도의 독립된 일반 함수로 선언) std::string Stringify(const char *s) { return "\"" + std::string(s) + "\""; } ``` 두 방식은 호출 형태에 따라 동작이 달라진다: - **`Stringify("hello")`처럼 함수 이름 뒤에 `<...>`를 붙여서 호출할 때:** - 호출할 때 ``처럼 꺾쇠를 명시하면, 컴파일러는 **방법 2 같은 일반 오버로드 함수는 아예 후보에서 제외**하고 오직 `template`으로 선언된 함수들 중에서만 찾는다. 따라서 방법 2로만 오버로딩해 두면 후보에서 빠져 **Primary Template**이 호출(`"hello"`)되는 반면, **방법 1**(`template <>`)은 해당 `template`에 속하므로 특수화 버전이 정상 호출(`"\"hello\""`)된다. - **그럼에도 `<...>` 없이 인자 추론으로 부르는 일반 호출(`Stringify("hello")`)에서는 왜 `template <>` 대신 일반 함수 오버로딩을 권장하는가?** 1. **암묵적 타입 변환 및 pointer decay 미적용:** - **방법 1 (`template <>` 특수화):** 독립된 오버로드 후보가 아니라 **Primary Template의 타입 추론이 끝난 뒤에야 일치 여부를 확인하는 부속 구현**이다. `Stringify("hello")`를 호출하면 문자열 리터럴 `"hello"`의 실제 타입은 포인터가 아니라 배열 `const char[6]`이고, Primary Template의 매개변수가 참조(`const C&`)이므로 pointer decay 없이 `C`가 `char[6]`으로 추론된다. 이후 컴파일러는 `char[6]`에 대한 특수화가 있는지만 찾을 뿐 `const char*`로의 변환을 시도하지 않으므로, 방법 1은 무시되고 **Primary Template**이 호출(`"hello"`)되어 버린다. - **방법 2 (일반 함수 오버로딩):** 1차 Overload Resolution 후보로 직접 참여하며 암묵적 타입 변환과 pointer decay가 허용된다. `const char[6]`이 `const char*`로 pointer decay되어 방법 2와 매칭되고, Primary Template(`Stringify`)과 변환 등급(Exact Match)이 동률일 때 C++ 규칙상 **일반 함수가 template 함수보다 우선 선택**되므로 의도대로 **방법 2**가 호출(`"\"hello\""`)된다. 2. **Function Template은 Partial Specialization 불가:** 포인터(`T*`)나 컨테이너(`std::vector`) 등 패턴별 분기는 어차피 함수 오버로딩으로만 작성할 수 있다. 3. **Overload Resolution 우선순위 함정 (Herb Sutter's Guideline):** 위 1번과 같은 이유로, Function template의 Explicit Specialization은 1차 오버로딩 후보 선택에 직접 참여하지 못하고 부모인 Primary Template이 먼저 선택된 뒤에야 적용되므로, 다른 오버로드 함수(`template void f(T*)` 등)와 섞일 때 직관과 다르게 무시될 수 있다. #### 실무 기준: 언제 반드시 `template <>`를 써야 하는가? | 상황 | 권장 방식 | 이유 | | :--- | :--- | :--- | | **인자로 타입 추론이 가능한 일반 함수** (`Stringify("hello")`, `compare(1, 0)`) | **일반 함수 오버로딩** | 암묵적 타입 변환이 동작하고 Overload Resolution 규칙이 직관적임 | | **Class / Struct Template** (`std::hash`, Type Traits 등) | **`template <>` Full / Partial Specialization** | class에는 오버로딩 개념이 없으므로 특정 타입 구현을 정의할 때 필수 | | **매개변수 타입이 같고 반환 타입만 ``로 구분되는 함수** (`Parse("8080")`, `Parse("3.14")`) | **`template <>` Explicit Specialization 필수** | C++에서 **매개변수가 같고 반환 타입만 다른 함수는 오버로딩이 불가능**하여 컴파일 에러가 나므로, 반드시 `template <>`로 특수화해야 함 | ```cpp // 매개변수가 std::string_view로 동일하고 반환 타입 T만 다른 경우: // 일반 함수 오버로딩은 컴파일 에러가 나므로 반드시 template <>을 사용 template T Parse(std::string_view s); template <> int Parse(std::string_view s) { return std::stoi(std::string(s)); } template <> double Parse(std::string_view s) { return std::stod(std::string(s)); } // 호출부: int port = Parse("8080"); double pi = Parse("3.14"); ```