回復網友一個關于模板的問題
????在我的http://www.shnenglu.com/cc/archive/2005/12/30/2292.html?這篇文章下面有一個網友留言問了在Dev-C++中使用模板出現的一個問題,今天終于有了時間我試驗了一下。
?? 他的問題是:
我有個dev?c
++
的?模板函數調用錯誤的問題請教!?
template?
<
typename?Type
>
?
inline?Type?max(?Type?t1,?Type?t2?)?
{?
return
?t1?
>
?t2?
?
?t1?:?t2;?}?
template?
<
typename?elemType
>
?
inline?elemType?max(?
const
?vector
<
elemType
>
?
&
vec?)?
{?
return
?
*
max_element(?vec.begin(),?vec.end()?);?}?
template?
<
typename?arrayType
>
?
inline?arrayType?max(?
const
?arrayType?
*
parray,?
int
?size?)?
{?
return
?
*
max_element(?parray,?parray
+
size?);?}?
上述是我在頭文件中聲明的模板函數?
在cpp文件中調用,出現錯誤?
note?D:\ACpp\moban\mb.h:
15
?candidates?are:?Type?max(Type,?Type)?[with?Type?
=
?
int
]?
但是在vc?和bcb中良好。。
? 我沒有他的全部代碼,也不知道他的調用文件是怎么寫的。
根據他的這些代碼,我寫了一個簡單的程序
程序一? 是一個頭文件,定義了模板
程序一
#include?
<
algorithm
>
#include?
<
vector
>
using
?
namespace
?std;
template
<
typename?Type
>
inline?Type?max(Type?t1,Type?t2)
{
????
return
?t1
>
t2
?
t1:t2?;
}
template
<
typename?elemType
>
inline?elemType?max(
const
?vector
<
elemType
>&
?vec)
{
????
return
?
*
max_element(vec.begin(),vec.end());
}
template
<
typename?arrayType
>
inline?arrayType?max(
const
?arrayType
*
parray,
int
?size)
{
????
return
?
*
max_element(parray,parray
+
size);
}
?? 程序二是 調用這個模板的例子
#include<iostream>
#include<vector>
#include"max.h"
using?namespace?std;
int?main(){
cout<<::max(2,3)<<endl;
????vector<int>?v1;
????v1.push_back(2);
????v1.push_back(8);
????v1.push_back(5);
????v1.push_back(1);
????cout<<::max(v1)<<endl;
????float?v2[10]={1,4,56,78,111,32,443,3,12,45};
????cout<<::max(v2,10)<<endl;
????getchar();
????}
程序能夠正常運行,結果是
??
3
8
443
證明這個程序在Dev-c++下面是能夠正常運行的,不知道這個朋友哪里寫的有問題,總的來看Dev-c++應該還是不錯的,如果有問題,我們最好先檢查一下自己的代碼。