C++向函数模版传递 const类型,数组类型
来源:互联网 发布:js的初始化 编辑:程序博客网 时间:2024/06/06 07:02
1)向模版传递 const类型
template <typename T > void fun( T &a)
{
int s =100;
T p = s;
p+= 1;
printf("%d \n",p);
}
int main()
{
int i = 100;
const int & p = i;
fun(p); //此时的函数式fun<const int> (const int &a);
}
VS2010中编译错误:
e:\source\mian\mian\mian.cpp(24): error C3892: 'p' : you cannot assign to a variable that is const
1> e:\source\mian\mian\mian.cpp(36) : see reference to function template instantiation 'void fun1<const int>(T &)' being compiled
1> with
1> [
1> T=const int
1> ]
2.模版为const 类型
template <typename T > void fun( const T &a)
{
int s =100;
T p = s;
p+= 1;
printf("%d \n",p);
}
int main()
{
int i = 100;
const int & p = i;
fun(p); //此时的函数式fun< int> (const int &a); T =int
}
编译通过;3)传递非const类型
template <typename T > void fun( const T &a)
{
int s =100;
T p = s;
p+= 1;
printf("%d \n",p);
}
int main()
{
int i = 100;
int & p = i;
fun(p); //此时的函数式fun< int> (const int &a); T =int
}
编译通过与第2中一样
小结:如果模版是非const T,实参的类型将如实传递得T,即 T = const int;
若果模版有const,实参类有无const ,模版中的T 都是非const类型,即T =int;
二、向模版传递数组
第四版C++ Prime 539 页说不能向模版传递 数组类型,因为不能转换成 int *类型;
不过在VS2010中可以,在 Linux G++也可,甚至可以用传递进来的类型之间,建立一个数组。
1)想引用传递数组
template <typename T > void fun( T &a)
{
printf("template %d\n",a[1]);
T s;//可以直接用这种类型建立个数组。
for(int i=0; i < 9; i++)
{
s[i] = i;
std::cout << s[i] << std::endl;
}
}
int _tmain(int argc, WCHAR* argv[])
{
int a[10] = {1,2,3,4,5,6,7,8,9,10};
fun(a);//此时的函数是fun<int [10]> ( int (&a) [10] ),即 T = int [10]
return 0;
}
2)数组类型的引用
int a[10] = {1,2,3,4,5,6,7,8,9,10};
//int (&arry)[10] = a;数组类型的引用。。
int (&arry)[10] 可以声明为函数的形参,赋值的时候编译器会检查 数组大小是否与 自身的引用类型一致。
int a1[9] = {1,2,3,4,5,6,7,8,9,};
int (&arry1)[10] = a1; --------出错。
总结:虽然这些东西乱起八糟,只是给编译器看到东西,引用只不过简单的使用 指针。
无论什么类型的引用还是地址来表示,数组传递给引用只不过传递地址而已。
而用引用取数组内容简化了用指针取数组,这些由编译器来做。
- C++向函数模版传递 const类型,数组类型
- 使用python向C语言的链接库传递数组、结构体、指针类型的数据
- c 向函数传递多维数组
- c 向函数传递多维数组
- 向函数传递数组
- C++------const类型定义
- C++:关于const类型
- 如何通过引用向 MASM 传递常见 C 类型
- C语言数组类型以及函数类型的定义
- [跨平台C++] 返回const char* 类型的函数样板
- c/c++中const成员函数的返回值类型
- Android使用NDK---函数参数传递-基本类型和数组
- C/C++中二维数组作函数形参时,调用函数时,可传递的实参类型的小结
- 向函数传递二维数组
- Shell 向函数传递 数组
- C++ 向函数传递数组
- const 作为函数返回类型
- const类型的成员函数
- 托福IBT考试内容及各部分计分方法
- hibernate:list与iterator区别
- 黑马程序员_银行业务调度
- Java中的EL和JSTl
- 我的2012
- C++向函数模版传递 const类型,数组类型
- 黑马程序员-----线程
- Android的消息提示:Toast与Notification的使用
- StringBuilder与StringBuffer的区别
- 深入探讨C++中的引用
- HDU 4409 Family Name List 简单树操作
- 《野蛮妈妈结婚记》 观后感
- 哈希函数(Hash function)简介
- 正确理解c/c++中字符连在一起的运用