[問題] Template of Template?
看板C_and_CPP作者RouterHsieh (醉臥美人膝,醒掌天下權)時間10年前發表 (2015/01/04 04:24), 10年前編輯推噓3(3推 0噓 6→)留言9則, 5人參與討論串1/1
在下今天正在練習template和function overloading的時候遇到一個問題,
(其實是Essential C++這本書的習題2.6延伸的)
假設我現在有兩個以下的template:
template <typename Type>
Type my_max(vector<Type> &tvec)
{
Type max = tvec[0];
for (int i = 1; i < tvec.size(); i++) {
if (tvec[i] > max)
max = tvec[i];
}
return max;
}
template <typename Type>
Type my_max(Type *tarr, int size)
{
Type max = tarr[0];
for (int i = 1; i < size; i++) {
if (tarr[i] > max)
max = tarr[i];
}
return max;
}
基本上我的my_max函式要做的很簡單,就是要能夠從vector/array當中,
把值最大的挑出來然後回傳。
當然vector/array的差別在於前者知道自己的size,但後者不知道。
所以當這個函式(my_max)用在array上的時候必須多傳入一個size的參數才行。
(因此在這裡可以用function overloading來解決)
我在想的是,既然上面兩個template function長的其實很像的情況下,
有可能再進一步的把上面這兩個template function化簡成單一的template嗎@@
(還是說其實這種狀況原本就是要用function overloading來解決?)
在下才剛開始學C++而已,所以可能問了個蠢問題,還請大家不吝指正,感謝~~
--
There is no secret behind the source code.
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 72.181.136.182
※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1420345455.A.6CD.html
※ 編輯: RouterHsieh (72.181.136.182), 01/04/2015 12:29:22
→
01/04 12:30, , 1F
01/04 12:30, 1F
推
01/05 03:25, , 2F
01/05 03:25, 2F
→
01/05 03:25, , 3F
01/05 03:25, 3F
推
01/06 20:55, , 4F
01/06 20:55, 4F
推
01/07 01:48, , 5F
01/07 01:48, 5F
→
01/07 01:48, , 6F
01/07 01:48, 6F
→
01/07 01:49, , 7F
01/07 01:49, 7F
→
01/07 11:47, , 8F
01/07 11:47, 8F
→
01/07 15:23, , 9F
01/07 15:23, 9F