[問題] 我對 template 的理解是不是有錯誤?
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
Code::Blocks
問題(Question):
下列這個簡單的函式沒有問題:
int *alloc_array(int w)
{
int *arr = (int *)malloc(w*sizeof(int));
if (arr == NULL)
exit(1);
return arr;
}
但是若改寫成函式範本:
template <typename T>
T *alloc_array(int w)
{
T *arr = (T *)malloc(w*sizeof(T));
if (arr == NULL)
exit(1);
return arr;
}
我以為很合理,結果使用函式時 GCC 馬上報錯:
error: no matching function for call to 'alloc_array(int)'
是我對 template 的理解錯了嗎?
補充說明(Supplement):
我知道在 C++ 寫這個函式沒什麼意義
實際上這也的確是為了測試故意寫的東西
我只是很想搞懂為什麼這樣子行不通而已......@@
--
琴劍六記 百萬字武俠長篇連載
http://gs.cathargraph.com
直接閱讀《琴劍六記》
http://gs.cathargraph.com/p/list.html
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 219.84.0.111
→
11/28 22:46, , 1F
11/28 22:46, 1F
→
11/28 22:49, , 2F
11/28 22:49, 2F
→
11/28 22:51, , 3F
11/28 22:51, 3F
推
11/28 22:57, , 4F
11/28 22:57, 4F
→
11/28 22:57, , 5F
11/28 22:57, 5F
→
11/28 22:58, , 6F
11/28 22:58, 6F
→
11/28 22:58, , 7F
11/28 22:58, 7F
→
11/28 23:08, , 8F
11/28 23:08, 8F
→
11/28 23:15, , 9F
11/28 23:15, 9F
→
11/28 23:16, , 10F
11/28 23:16, 10F
→
11/28 23:16, , 11F
11/28 23:16, 11F
→
11/28 23:16, , 12F
11/28 23:16, 12F
→
11/28 23:16, , 13F
11/28 23:16, 13F
→
11/28 23:17, , 14F
11/28 23:17, 14F
→
11/28 23:19, , 15F
11/28 23:19, 15F
→
11/28 23:19, , 16F
11/28 23:19, 16F
→
11/28 23:30, , 17F
11/28 23:30, 17F
→
11/28 23:33, , 18F
11/28 23:33, 18F
→
11/28 23:34, , 19F
11/28 23:34, 19F
→
11/28 23:45, , 20F
11/28 23:45, 20F
推
11/29 00:39, , 21F
11/29 00:39, 21F
→
11/29 01:39, , 22F
11/29 01:39, 22F
→
11/29 02:34, , 23F
11/29 02:34, 23F
→
11/29 02:34, , 24F
11/29 02:34, 24F
→
11/29 02:35, , 25F
11/29 02:35, 25F
推
11/29 23:14, , 26F
11/29 23:14, 26F