c++ - template non-type parameter and template instantiation

in C++, there are function template, where you can have two type of template paramters, one is normal template parameter, which stands for a type, while the other is a template non-type parameter, which represents a potential value, such as the size of an array . 

 

 

template instantiation is the process of an individual function constructed given a set of one or more actual type or values (for template non-type parameters).

 

 

the template instantiation is capable of deducing the value of those template non-type parameter, below shows the example and the reason analysis belows it. 

 

 

NOTE: The process of determine the types and values of the templates argument from the type of type of the function argument is called "template argument deduction", we will have separate chapter t elaborte on this. 

 

 

 

/**
* @Summary
*   template non-type parameter 
* @Comment:
*   a non-type parameter consists of ordinary parameter declaration, A template non-type parameter indicate a constant in the template definition
*   an example of the non-type parameter is 'size' which represents the size of an array to which arr refers as follow.
*   
* below shows something about the template function initialization when non-type parameter is instantiated
*
* the results show that the compiler should be able to infer the value of the non-type parameter if it can, and there is no need to provide a explicit 
* value for such parameter, in this case 
* since 
*  int ia[] = { 10, 7, 14, 3, 25};
* has know size of 
*  5
* and when you call
*  min(ia);
* it will match agains the definition
*  Type min(const Type (&r_arr)[size])
* so we know 
*  size == 5
* so you don't need to write as 
*  min(ia, 5);
* and it will error, if you try to 
*  min(ia, 5)
*/


template<typename Type, int size>
Type min(const Type (&r_arr)[size]) { 
	Type min_val = r_arr[0];
	for (int i = 1; i < size; i++) { 
		if (r_arr[i] < min_val) {
			min_val = r_arr[i];
		}
	}

	return min_val;
}

// #include <iostream>
using namespace std;
// suppose we hve two array whose size is known at conpile time
int ia[] =  { 10, 7, 14, 3, 25 } ;
double da[] = { 10.2, 7.1, 14.5, 3.2, 25.0, 16,8 } ;




int _tmain(int argc, _TCHAR* argv[])
{

	int i = min(ia);
	if (i != 3) { 
		cout << "?? oops: integer min() failed\n";
	} else { 
		cout << "!!OK: integer min() worked\n";
	}


	// instantiation of min() for an array o f6 doubles
	// with type => double, size => 6
	double d = min(da);
	if (d != 3.2) { 
		cout << "??oops: double min() failed\n";
	} else { 
		cout << "!!ok: double min() worked\n";
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值