Chinaunix首页 | 论坛 | 博客
  • 博客访问: 748441
  • 博文数量: 239
  • 博客积分: 60
  • 博客等级: 民兵
  • 技术积分: 1045
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-22 18:25
文章分类

全部博文(239)

文章存档

2019年(9)

2018年(64)

2017年(2)

2016年(26)

2015年(30)

2014年(41)

2013年(65)

2012年(2)

分类: C/C++

2014-04-01 17:16:15

    C++函数模板从数组中推导类型。可以从数组中推导出来的有数组类型和大小。
[Example:

点击(此处)折叠或打开

  1. #include <iostream>
  2. using namespace std;

  3. template<int i> void form1(int a[10][i])
  4. {
  5.     cout<<"[template void form1(int a[10][i])] i = "<<i<<endl;
  6. }

  7. template<int i> void form2(int a[i][20])
  8. {
  9.     cout<<"[template void form2(int a[i][20])] i = "<<i<<endl;
  10. };

  11. template<int i> void form3(int (&a)[i][20])
  12. {
  13.     cout<<"[template void form3(int (&a)[i][20])] i = "<<i<<endl;
  14. };

  15. template<typename Type, int i> void form4(Type (&a)[i][20])
  16. {
  17.     cout<<"[template void form4(Type (&a)[i][20])]"<<"\t"
  18.         <<"i = "<<i<<"\t"
  19.         <<"Type = "<<typeid(Type).name()<<endl;
  20. };

  21. void g()
  22. {
  23.     int v[10][20];
  24.     form1(v); // OK: i deduced to be 20
  25.     form1<20>(v); // OK
  26.     //form2(v); // error: cannot deduce template-argument i
  27.     form2<10>(v); // OK
  28.     form3(v); // OK: i deduced to be 10
  29.     form4(v); // OK: i deduced to be 10, Type deduce to int
  30. }

  31. int main(int argc, char* argv[])
  32. {
  33.     g();
  34.     return 0;
  35. }

Result:

点击(此处)折叠或打开

  1. [template<int i> void form1(int a[10][i])] i = 20
  2. [template<int i> void form1(int a[10][i])] i = 20
  3. [template<int i> void form2(int a[i][20])] i = 10
  4. [template<int i> void form3(int (&a)[i][20])] i = 10
  5. [template<typename Type, int i> void form4(Type (&a)[i][20])]    i = 10    Type = int

结果分析:
    Except for reference and pointer types, a major array bound is not part of a function parameter type and cannot be deduced from an argument.
— end example]
[14.8.2.5.15  Deducing template arguments from a type    ISO/IEC 14882:2011(E)]
阅读(1202) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~