C 模板函式的型別推導

2021-10-08 10:44:30 字數 722 閱讀 6923

我在用泛型程式設計寫二維vector的排序模板時,寫出這樣乙個**:

//vector的字典序比較,v1=v2是false

templatebool cmp(vector&v1,vector&v2)

編譯結果:

1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm(3802) : 參見「std::sort」的宣告

1>c:\users\z00454773\documents\visual studio 2010\projects\20191228.cpp\20191228.cpp\csimsgeek.cpp(273): error c2780: 「void std::sort(_ranit,_ranit)」: 應輸入 2 個引數,卻提供了 3 個

這就很奇怪了,一般在sort裡面用自定義排序函式,就是加函式指標啊!

很快,我就想到了,這裡的cmp是模板函式,它是需要根據型別引數來例項化的。

也就是說,模板函式直接呼叫是可以自動推導型別的,但是如果要用做函式指標的話,需要傳入型別引數才能例項化

正確**:

//vector的字典序排序

templatevoid sortvector(vector>&v)

C 模板型別推導

內容參考 effective modern c 中的條款1 int x 27 const int cx x const int rx x const int p x 1.paramtype是個指標或引用,但不是個萬能引用 去引用不去const template void f t param f x ...

模板型別推導

param引用無const修飾template void f t param int x 1 const int cx x const int rx x f x f cx f rx 函式呼叫 t的型別 param的型別 f x intint f cx const int const int f rx...

模板型別推導 auto推導

effective modern c 果然是神書,乾貨滿滿,簡單記錄下。item1 模板推倒 典型的模板函式 temlate void fn paramtype param 要記住的東西 在模板型別推導的時候,有引用特性的引數的引用特性會被忽略 在推導通用引用引數的時候,左值會被特殊處理 在推導按值...