关于c++模板函数的声明

aa1459525376 2018-05-21 05:08:57
初学c++,遇到一个问题,在使用模板函数时,在main函数下定义一个模板函数,在main函数声明了,但编译报错,
报错:
2.6.cpp:10:1: error: ‘elemTrype’ does not name a type
elemTrype max1(elemTrype a,elemTrype b);
然后我把函数的定义放在main函数之前,在把声明注释掉发现程序能正常编译与运行,我想问模板函数不能放在main之前声明吗?


#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

elemTrype max1(elemTrype a,elemTrype b);
elemTrype max1(vector<elemTrype> a);



int main(void)
{
int arry[5] = {1,6,3,4,5};
vector<int> a(arry,arry+5);

float arryf[5] = {1.1,6.1,3.1,4.1,5.1};
vector<float> af(arryf,arryf+5);


cout << "max1 is :" << max1(a) << endl;
cout << "max1 is :" << max1(af) << endl;
cout << "max1 is :" << max1(2,5) << endl;
cout << "max1 is :" << max1(2.1,2.5) << endl;

return 0;
}

template <typename elemTrype>
elemTrype max1(elemTrype a,elemTrype b)
{
return (a>b ? a : b);
}

template <typename elemTrype>
elemTrype max1(vector<elemTrype> a)
{
return *max_element(a.begin(),a.end());
}


...全文
374 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
aa1459525376 2018-05-21
  • 打赏
  • 举报
回复
哦,这我就懂了,谢谢了。
donjin9 2018-05-21
  • 打赏
  • 举报
回复
不加的话,编译器到这应该不知道elemTrype是什么东西吧。
aa1459525376 2018-05-21
  • 打赏
  • 举报
回复
我试了,还真的是这个原因,我想问一下,为什么要加上template <typename elemTrype>
donjin9 2018-05-21
  • 打赏
  • 举报
回复
声明也要加上template <typename elemTrype>吧。

64,683

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧