docs(10_Wiki): Topic_Business/General/Graphic/Programming을 Topics/ 하위로 이동
최상위 10_Wiki/Topic_*였던 4개 카테고리 폴더를 10_Wiki/Topics/Topic_* 로 재배치. 콘텐츠 변경 없음(순수 폴더 이동) — Topics/ 하위 나머지 폴더는 이미 지난 커밋에서 전부 정리된 상태(잔존 항목은 에이전트 운영 상태 및 사용자가 보존을 요청한 업데이트0615/무제 3.canvas 뿐).
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
---
|
||||
id: cpp-templates
|
||||
title: "C++ Templates"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["template keyword", "typename T", "generic programming", "C++ 템플릿"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.88
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["cpp", "programming-language", "w3schools", "templates", "generics"]
|
||||
raw_sources: ["https://www.w3schools.com/cpp/cpp_templates.asp"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[CPP Templates]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Templates solve the EXACT problem Function Overloading solved for a FIXED set of types, but generalize it to work with ANY type without writing a separate version for each — `template <typename T> T add(T a, T b)` handles `int`, `double`, or any other type with ONE definition, whereas overloading (from the Functions section) required a separate `plusFunc(int...)` and `plusFunc(double...)` pair, meaning templates are the more powerful, general-purpose evolution of what overloading only approximated for specific type combinations. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Function template** — `template <typename T> return_type function_name(T parameter) { ... }`; `T` is a placeholder for ANY data type, resolved at each CALL site. [S1]
|
||||
- **Explicit type specification** — `add<int>(5, 3)` or `add<double>(2.5, 1.5)` tells the compiler which concrete type `T` should be for that specific call. [S1]
|
||||
- **Class template** — `template <typename T> class ClassName { ... };` lets an entire class (members, methods) work generically with any type, instantiated per-type (`Box<int>`, `Box<string>`). [S1]
|
||||
- **Multiple template parameters** — `template <typename T1, typename T2> class Pair { ... };` handles TWO independently-typed values in one generic class (`Pair<string, int>`, `Pair<int, double>`). [S1]
|
||||
- **File placement constraint** — templates must be defined in the SAME file where they're used (typically the header/`.h` file), unlike ordinary functions which can be split across declaration/definition files. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- A generic add function working for both int and double: `template <typename T> T add(T a, T b) { return a + b; } cout << add<int>(5, 3); cout << add<double>(2.5, 1.5);`. [S1]
|
||||
- A generic class storing any single value type: `template <typename T> class Box { public: T value; Box(T v) { value = v; } void show() { cout << "Value: " << value << "\n"; } }; Box<int> intBox(50); Box<string> strBox("Hello");`. [S1]
|
||||
- A generic class handling two independently-typed values: `template <typename T1, typename T2> class Pair { public: T1 first; T2 second; Pair(T1 a, T2 b) { first = a; second = b; } void display() { cout << "First: " << first << ", Second: " << second << "\n"; } }; Pair<string, int> person("John", 30); Pair<int, double> score(51, 9.5);`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **템플릿과 오버로딩은 같은 목표를 다른 방식으로 해결**: 오버로딩은 각 타입 조합마다 별도 함수 정의가 필요했지만, 템플릿은 하나의 정의로 모든 타입에 대응한다는 점에서 오버로딩보다 더 일반화된 해법임이 확인됨. [S1]
|
||||
- **템플릿은 같은 파일에 정의되어야 함**: 일반 함수와 달리 템플릿은 선언과 정의를 분리할 수 없고 보통 헤더(.h) 파일에 함께 두어야 한다는 제약이 명시됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
이름/나이(문자열+정수), ID/점수(정수+실수)처럼 서로 다른 두 타입 조합을 하나의 Pair 템플릿 클래스로 처리하는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
A generic class template handling two independently-typed values (C++):
|
||||
```cpp
|
||||
template <typename T1, typename T2>
|
||||
class Pair {
|
||||
public:
|
||||
T1 first;
|
||||
T2 second;
|
||||
Pair(T1 a, T2 b) { first = a; second = b; }
|
||||
void display() { cout << "First: " << first << ", Second: " << second << "\n"; }
|
||||
};
|
||||
int main() {
|
||||
Pair<string, int> person("John", 30);
|
||||
Pair<int, double> score(51, 9.5);
|
||||
person.display();
|
||||
score.display();
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.88
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C++ Tutorial]]
|
||||
- **관련 개념:** [[CPP Friend Function]], [[CPP Function Overloading]], [[CPP Namespaces]], [[CPP Vectors]]
|
||||
- **참조 맥락:** 다형성 및 고급 OOP 섹션 마지막 — 네임스페이스(Namespaces) 섹션으로 이어짐, STL 컨테이너(Vectors 등)에서 템플릿이 실제로 쓰이는 방식과 직접 연결.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C++ Templates — https://www.w3schools.com/cpp/cpp_templates.asp
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C++ Templates" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
Reference in New Issue
Block a user