程序让生活更美好

半亩方塘 天光云影

  C++博客 ::  :: 新随笔 :: 联系 ::  :: 管理 ::
  55 随笔 :: 4 文章 :: 202 评论 :: 0 Trackbacks

回复网友一个关于模板的问题


    在我的http://www.cppblog.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++应该还是不错的,如果有问题,我们最好先检查一下自己的代码。
posted on 2006-04-16 22:23 北风之神007 阅读(304) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理