C++(11):模板参数类型推导之传值类型

传值类型模板参数

template<class T>
void fn(T param)

param是通过传值的方式传递的,也就是说t这个形参是通过函数fn被调用时的实参拷贝赋值的,param是一个全新的对象,因此实参的常量性(const),引用性都不会被传递到形参param上:

#include <iostream>
#include <typeinfo>
using namespace std;

template<class T>
void fn(T param)
{
	cout<<" "<<is_same<T, int>::value;
	cout<<" "<<is_same<T, const int>::value;
	cout<<" "<<is_same<T, const int&>::value<<endl;
}

int main ()
{
	int x = 1;
	const int  cx = x;
	const int& rx = x;
	fn(x);    //输出:1 0 0
	fn(cx);   //输出:1 0 0
	fn(rx);   //输出:1 0 0
    return 0;
}

可见实参的常量性及引用性都不会传递到形参param上

对于实参指针的const性,也不例外,不过需要指出的是对于指针,可以声明指针指向对象的常量性及指针本身的常量性:

const char * const p = "hello";

第一个const即 * 左边的const是用来修饰指针所指向的类型,也就是说指针指向的内容是const

第二个const即 * 右边的const是用来修饰指针本身的,也就是说指针本身是const

当param是传值的是指针类型时,修饰指针所指向类型的const会被传递给param,但是修饰指针本身的const不会被传递:

#include <iostream>
#include <typeinfo>
using namespace std;

template<class T>
void fn(T param)
{
	cout<<is_same<T, char *>::value;
	cout<<" "<<is_same<T, const char *>::value;
	cout<<" "<<is_same<T, const char * const>::value<<endl;
}

int main ()
{
	char *p1 = "hi";
	const char *p2 = "hi";
	const char * const p3 = "hi";
	fn(p1);    //输出:1 0 0
	fn(p2);    //输出:0 1 0
	fn(p3);    //输出:0 1 0
    return 0;
}


版权声明:本文为jiemashizhen原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。