C++函数模板从数组中推导类型。可以从数组中推导出来的有数组类型和大小。
[Example:
-
#include <iostream>
-
using namespace std;
-
-
template<int i> void form1(int a[10][i])
-
{
-
cout<<"[template void form1(int a[10][i])] i = "<<i<<endl;
-
}
-
-
template<int i> void form2(int a[i][20])
-
{
-
cout<<"[template void form2(int a[i][20])] i = "<<i<<endl;
-
};
-
-
template<int i> void form3(int (&a)[i][20])
-
{
-
cout<<"[template void form3(int (&a)[i][20])] i = "<<i<<endl;
-
};
-
-
template<typename Type, int i> void form4(Type (&a)[i][20])
-
{
-
cout<<"[template void form4(Type (&a)[i][20])]"<<"\t"
-
<<"i = "<<i<<"\t"
-
<<"Type = "<<typeid(Type).name()<<endl;
-
};
-
-
void g()
-
{
-
int v[10][20];
-
form1(v); // OK: i deduced to be 20
-
form1<20>(v); // OK
-
//form2(v); // error: cannot deduce template-argument i
-
form2<10>(v); // OK
-
form3(v); // OK: i deduced to be 10
-
form4(v); // OK: i deduced to be 10, Type deduce to int
-
}
-
-
int main(int argc, char* argv[])
-
{
-
g();
-
return 0;
-
}
Result:
-
[template<int i> void form1(int a[10][i])] i = 20
-
[template<int i> void form1(int a[10][i])] i = 20
-
[template<int i> void form2(int a[i][20])] i = 10
-
[template<int i> void form3(int (&a)[i][20])] i = 10
-
[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)]
阅读(1258) | 评论(0) | 转发(0) |