目錄
What Are Templates?
Function Templates vs Class Templates
Function Templates
Class Templates
Template Parameters: Types and Values
Tips for Writing Your Own Templates
Final Thoughts
首頁 後端開發 C++ C關於模板和通用編程的教程

C關於模板和通用編程的教程

Jun 30, 2025 am 12:48 AM

C 模板通過編譯時類型替換實現泛型編程,減少重複邏輯。它分為函數模板與類模板,前者如template T add(T a, T b)可自動推導類型,後者如template class Box用於創建通用容器;模板參數不僅支持類型(typename T),也支持值(如template class StaticArray),且可混合使用;編寫模板時應從簡單入手,優先使用typename,注意錯誤定位困難及操作符有效性,C 20的Concepts可用於約束類型,提升代碼安全性和可讀性。

C   tutorial on templates and generic programming

Templates in C are one of the most powerful tools for writing generic code — meaning you can write functions and classes that work with any data type, without duplicating logic. It's what makes things like std::vector or std::map possible, where they adapt to whatever type you throw at them.

C   tutorial on templates and generic programming

What Are Templates?

At their core, templates let you define functions or classes using placeholder types. The compiler then generates the real code when it sees which types you're actually using.

C   tutorial on templates and generic programming

For example:

 template <typename T>
T add(T a, T b) {
    return ab;
}

Here, T is a placeholder. When you call add<int>(1, 2) or add<double>(1.5, 2.3) , the compiler creates two separate versions of this function under the hood.

C   tutorial on templates and generic programming

This is different from just using void* or inheritance-based polymorphism because templates are resolved at compile time — no runtime overhead.


Function Templates vs Class Templates

There are two main kinds of templates: function templates and class templates.

Function Templates

These are used to create families of functions. You've already seen a basic example above.

You don't always need to specify the template parameter explicitly. If the compiler can deduce it from the arguments, it will:

 int result = add(3, 4); // Compiler deduces T as int

But if your function doesn't use all parameters in a way that allows deduction (like if they're defaulted), you'll have to specify the type manually.

Class Templates

These are used when you want a class to work with different types. A classic example is a container:

 template <typename T>
class Box {
public:
    Box(T value) : value_(value) {}
    T get() const { return value_; }
private:
    T value_;
};

Then you can do:

 Box<int> intBox(42);
Box<std::string> stringBox("hello");

Just like with functions, the compiler creates a new version of the class for each type used.


Template Parameters: Types and Values

Templates aren't limited to just type parameters ( typename T ). You can also pass values as template parameters.

For example:

 template <int Size>
class StaticArray {
public:
    int data[Size];
};

Now you can do:

 StaticArray<10> arr; // Array of size 10 known at compile time

This is how fixed-size containers in libraries like Eigen or some embedded systems code work. These values must be known at compile time.

You can mix both type and value parameters:

 template <typename T, int N>
class ArrayWrapper {
    T data[N];
};

Tips for Writing Your Own Templates

  • Start simple : Don't overcomplicate templates early on. Just replace hardcoded types with T .
  • Use typename, not class : Both work, but typename is more general and preferred.
  • Be careful with template instantiation errors : Since templates are compiled only when used, errors might pop up far from where you wrote the code.
  • Avoid repeating yourself : If you find yourself writing nearly identical code for multiple types, templates are probably the solution.
  • Don't assume operators exist : If your template uses , make sure the type actually supports it. Concepts (in C 20) help enforce these assumptions.

Concepts are a newer feature that lets you constrain what types can be used with a template:

 template <std::integral T>
T multiply(T a, T b) {
    return a * b;
}

This ensures only integer-like types can be passed into multiply .


Final Thoughts

Templates are what make C so flexible without sacrificing performance. They're a bit tricky to start with, especially when dealing with complex instantiations or error messages, but once you understand how they work, you'll wonder how you ever wrote code without them.

It's not magic — just the compiler doing work ahead of time. And that's kind of the whole point of C .

以上是C關於模板和通用編程的教程的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT

Stock Market GPT

人工智慧支援投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

C自定義分配器示例 C自定義分配器示例 Sep 17, 2025 am 08:45 AM

自定義分配器可用於控制C 容器的內存分配行為,1.示例中的LoggingAllocator通過重載allocate、deallocate、construct和destroy方法實現內存操作日誌記錄;2.分配器需定義value_type和rebind模板,以滿足STL容器類型轉換需求;3.分配器構造與拷貝時觸發日誌輸出,便於追踪生命週期;4.實際應用包括內存池、共享內存、調試工具和嵌入式系統;5.C 17起construct和destroy可由std::allocator_traits默認處理

如何編譯和運行C程序 如何編譯和運行C程序 Sep 16, 2025 am 05:29 AM

InstallaC compilerlikeg usingpackagemanagersordevelopmenttoolsdependingontheOS.2.WriteaC programandsaveitwitha.cppextension.3.Compiletheprogramusingg hello.cpp-ohellotogenerateanexecutable.4.Runtheexecutablewith./helloonLinux/macOSorhello.exeonWi

如何在C中執行系統命令 如何在C中執行系統命令 Sep 21, 2025 am 04:35 AM

使用std::system()函數可執行系統命令,需包含頭文件,傳入C風格字符串命令,如std::system("ls-l"),返回值為-1表示命令處理器不可用。

如何使用CMAKE建立C項目? 如何使用CMAKE建立C項目? Sep 18, 2025 am 01:04 AM

創建項目目錄結構,包含CMakeLists.txt、src/和include/;2.編寫CMakeLists.txt,指定CMake版本、項目名稱、C 標準並添加可執行文件;3.使用mkdirbuild進入目錄並運行cmake..和cmake--build.進行編譯;4.通過add_executable添加多個源文件,用target_include_directories包含頭文件路徑;5.使用find_package查找外部庫並用target_link_libraries鏈接;6.通過tar

如何在C中使用堆棧 如何在C中使用堆棧 Sep 21, 2025 am 05:16 AM

C 的stack是STL中的容器適配器,遵循後進先出原則,需包含頭文件;通過push添加元素,pop移除頂部元素,top訪問棧頂,操作前應檢查是否為空,常用於表達式求值、回溯等場景。

如何在現代C中使用汽車 如何在現代C中使用汽車 Sep 24, 2025 am 04:59 AM

Theautokeywordletsthecompilerdeducevariabletypesfrominitializers,reducingverbosityandimprovingmaintainability.Itsimplifiescodewithcomplextypeslikeiteratorsandlambdas,supportsreferencesandconstqualifierstoavoidunnecessarycopies,andadaptsautomaticallyw

C抽像類示例 C抽像類示例 Sep 15, 2025 am 05:55 AM

抽像類是包含至少一個純虛函數的類,不能被實例化,必須作為基類被繼承,且派生類需實現其所有純虛函數,否則仍為抽像類。 1.純虛函數通過virtual返回類型函數名()=0;聲明,用於定義接口規範;2.抽像類常用於統一接口設計,如area()、draw()等,實現多態調用;3.必須為抽像類提供虛析構函數(如virtual~Shape()=default;),確保通過基類指針正確釋放派生類對象;4.派生類繼承後需重寫純虛函數,如Rectangle和Circle分別實現area()計算各自面積;5.可通過

如何在C中實現自定義迭代器 如何在C中實現自定義迭代器 Sep 20, 2025 am 01:13 AM

答案是定義包含必要類型別名和操作的類。首先設置value_type、reference、pointer、difference_type和iterator_category,然後實現解引用、遞增及比較操作,最後在容器中提供begin()和end()方法以返回迭代器實例,使其兼容STL算法和範圍for循環。

See all articles