免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3733 | 回复: 1

[C++] 模板类名如何用作模板实参? [复制链接]

论坛徽章:
0
发表于 2018-07-31 19:08 |显示全部楼层
如题,我想给一个模板函数传递STL容器的类型,下面这个代码是编译不过的。
如何修改才能让f能接受诸如vector,list这样的模板类参数呢?
谢谢
  
#include<vector>
#include<list>
#include<iostream>
using namespace std;
  
template<template<typename> class T, typename Elem>
void f(){
     T<Elem> t;
     t.push_back(1);
}
int main(){
     f<vector, int>();
     f<list, long>();
     return 0;
}

论坛徽章:
14
巨蟹座
日期:2013-11-19 14:09:4615-16赛季CBA联赛之青岛
日期:2016-07-05 12:36:0515-16赛季CBA联赛之广东
日期:2016-06-29 11:45:542015亚冠之全北现代
日期:2015-07-22 08:09:472015年辞旧岁徽章
日期:2015-03-03 16:54:15巨蟹座
日期:2014-12-29 08:22:29射手座
日期:2014-12-05 08:20:39狮子座
日期:2014-11-05 12:33:52寅虎
日期:2014-08-13 09:01:31巳蛇
日期:2014-06-16 16:29:52技术图书徽章
日期:2014-04-15 08:44:01天蝎座
日期:2014-03-11 13:06:45
发表于 2018-08-01 12:41 |显示全部楼层
为什么不直接
  1. #include <vector>
  2. #include <list>
  3. #include <iostream>
  4. using namespace std;
  5.   
  6. template<class CON>
  7. void f()
  8. {
  9.      CON t;
  10.      t.push_back( 1 );
  11. }

  12. int main()
  13. {
  14.      f<vector<int>>();
  15.      f<list<int>>();
  16.      return 0;
  17. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP