C STL 函式模板

2022-03-28 09:11:38 字數 2541 閱讀 6188

模板主要是為了泛型程式設計,做到與型別無關

1.函式模板定義

template

返回型別 函式模板名(呼叫形參表)

在返回型別,呼叫形參表和函式體中,所需要型別的地方都可以引用模板形參表中型別形參

templatea function(b arg)

2.使用

函式模板名《型別形參1,型別形參2,...>(呼叫實參表)

即用<>中的替換template<>中的內容

eg:

int i = function(1.23);

char c = function("hello");

3.型別引數

型別形參:前面必須帶有typename或class關鍵字.

型別實參:傳遞給函式模板的型別實參既可以是基本型別(char/int/double等),也可以是類型別(student/teacher),甚至可以是其他模板例項化的型別(string),同時傳遞給函式模板的型別實參必須滿足模板實現的具體要求, 否則將引發編譯錯誤.

#include using

namespace

std;

template

t add (t x, t y)

class

integer

friend ostream& operator

<< (ostream& os,integer const&i)

integer

const

operator+ (integer const& rhs) const

private

:

intm_var;

};int main (void

)

4.延遲編譯

每個函式模板事實上都要被編譯兩次:

(1)第一次是在編譯器看到該函式模板被定義的時候,這時的編譯器只對該函式模板做一般性的語法檢查(與型別無關),然後生成關於該函式模板的內部表示

(2)第二次是在編譯器看到該函式模板被呼叫的時候,在用所提供的型別實參,結合之前生成的內部表示中的型別形參,做與型別相關的語法檢查,並生成該函式模板的二進位制指令**.

5.隱式推斷

(1)如果函式模板呼叫引數(園括號裡的引數)的型別 相關與該模板的引數《尖括號裡的引數》,那麼在呼叫該函式模板的時候,即使不顯示指定模板引數,編譯器也有能力根據呼叫引數的型別隱式推斷出正確的模板引數型別,這就叫模板引數的隱式推斷.

(2)但是注意:如果編譯器隱式推斷的型別,和程式設計者所期望的型別不一致,有可能導致編譯錯誤.

#include #include 

using

namespace

std;

template

void

foo (t x, t y)

template

void bar (t const& x, t const&y)

template

r hum (t x)

void f1 (int x, int

y) {}

void f2 (double x, double

y) {}

int main (void

)

6.過載

與普通函式一樣,函式模板也可以形成過載關係,型別的約束性越強的版本越被有限選擇

#include #include 

#include

using

namespace

std;

//兩個任意型別值的最大值

templatet

const& max (t const& x, t const&y)

//兩個任意型別指標所指向目標的最大值

templatet* const& max (t* const& x, t* const&y)

//兩個字元指標所指向字串的最大值

char

const* const& max (char

const* const& x,char

const* const&y)

/*char const* max (char const* x,char const* y)

*///

三個任意型別值的最大值

templatet

const& max (t const& x, t const&y,

t const&z)

/*// 兩個字元指標所指向字串的最大值

char const* const& max (char const* const& x,char const* const& y)

*/int main (void

)

暫時就是這些了...

c STL中一些常用函式 模板

std floor 向下取整數 std ceil 向上取整數 std llround 最接近的整數 std numeric limits epsilon 最小雙精度小數 std numeric limits max 最大值std numeric limits min 最大值std ref 用於std...

模板 函式模板

c 程式設計 資料結構與程式設計方法 例15.8 利用函式過載技術,求兩個整數 字元 浮點數或字串中的較大值,需要編寫4個函式larger。而c 通過提供函式模板,簡化了過載函式據的過程。include using namespace std template type,模板的形參,用於確定函式的形...

函式模板和模板函式

1.函式模板的宣告和模板函式的生成 1.1函式模板的宣告 函式模板可以用來建立乙個通用的函式,以支援多種不同的形參,避免過載函式的函式體重複設計。它的最大特點是把函式使用的資料型別作為引數。函式模板的宣告形式為 template 返回型別 函式名 參數列 其中,template是定義模板函式的關鍵字...