设为首页 加入收藏

TOP

C++11 新特性之 变长参数模板
2015-07-24 05:57:56 来源: 作者: 【 】 浏览:5
Tags:特性 参数 模板
template 
  
   
void fun(ARGS ... args)
  

首先明确几个概念
1,模板参数包(template parameter pack):它指模板参数位置上的变长参数,例如上面例子中的ARGS

2,函数参数包(function parameter pack):它指函数参数位置上的变长参数,例如上面例子中的args


一般情况下 参数包必须在最后面,例如:

template 
  
   
void fun(T t,Args ... args);//合法

template 
   
     void fun(Args ... args,T t);//非法
   
  

有一个新的运算符:sizeof...(T) 可以用来获知参数包中打包了几个参数,注意 不是 参数所占的字节数之和。


#include 
  
   
using namespace std;

template 
   
     //Args:模板参数包 void func(Args ...args) //args:函数参数包 { cout << sizeof...(args) << endl; } int main() { func(1, 2, 3, 4, 5); //输出5 return 0; } 
   
  


函数实例
一个常用的技巧是:利用模板推导机制,每次从参数包里面取第一个元素,缩短参数包,直到包为空。

#include 
  
   
using namespace std;

template 
   
     void func(const T& t) { cout << t << endl; } template 
    
      //Args:模板参数包 void func(const T& t, Args ...args) //args:函数参数包 { cout << t << endl; func(args...); } int main() { func(1, 2, 3, 4, 5); return 0; } 
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇poj 2154 Color(polya计数 + 欧.. 下一篇CABasicAnimation学习Demo 包括了..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: