C ++ templates Reading Notes <1> function templates
* Instead of compiling a template into a single entity that can process any type, a different entity is generated from the template for no type of instantiated template parameters. * The process of replacing template parameters with specific types is called "instantiation" * The template is compiled twice: 1. Check the syntax 2 of the template itself before instantiation. During the instantiation, check whether all calls are valid * internal function templates, and do not specify the default template real parameters (class templates are acceptable ). * Real-parameter deduction of a function template: the type of the call parameter is constructed from the template parameter. Therefore, the template parameter and the call parameter are usually related. The real parameter deduction of the template is not suitable for the return type. * Eg: 1 template <typename T1, typename T2>
2 inline T1 max (T1 const & A, T2 const & B)
3 {
4 return a <B? B:;
5} Note: The return type cannot be a reference. If T2 type is returned, T2 needs to be converted to T1. This process creates a new local temporary variable. * Overload function template: A> A non-template function can coexist with a template function with the same name, and the template function can also be instantiated as a non-template function. B> automatic type conversion is not allowed for a template, but normal non-template functions are acceptable. Eg: 1 inline int const & MAX (INT const & A, int const & B)
2 {
3 return a <B? B:;
4}
5
6 template <typename T>
7 inline t const & MAX (T const & A, T const & B)
8 {
9 return a <B? B:;
10}
11
12 max (7.0, 42.0); // call Max <double>
13 max ('A', 'B'); // call Max <char>
14 max (7, 42); // call the int overload non-function Template
15 max <> (7, 42); // call Max <int> A>
16 max <double> (7, 42); // call Max <double> no real parameter deduction
17 max <'A', 42.7>; // call the INT-loaded non-function template. B> C> the declaration of all the overloaded versions of the function should be prior to the position where the function is called.
Copyright Disclaimer: This article is an original article and can be reproduced. However, you must use a hyperlink to indicate the original source and author information of the article. Please respect your labor achievements. Thank you!
Xiao Xiang's blog http://xfxsworld.cnblogs.com