📄 template.html
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head> <meta name="generator" content= "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org"> <title>template</title> <link href="../cppreference.css" rel="stylesheet" type="text/css"></head><body><table> <tr> <td> <div class="body-content"> <div class="header-box"> <a href="../index.html">cppreference.com</a> > <a href= "index.html">C/C++ Keywords</a> > <a href= "template.html">template</a> </div> <div class="name-format"> template </div> <div class="syntax-name-format"> Syntax: </div> <pre class="syntax-box"> template <class data-type> return-type name( parameter-list ) { statement-list; }</pre> <p>Templates are used to create generic functions and can operate on data without knowing the nature of that data. They accomplish this by using a placeholder data-type for which many other <a href= "../data_types.html">data types</a> can be substituted.</p> <div class="related-examples-format"> Example code: </div> <div class="related-examples"> <p>For example, the following code uses a template to define a generic swap function that can swap two variables of any type:</p> <pre class="example-code"> template<class X> void genericSwap( X &a, X &b ) { X tmp; tmp = a; a = b; b = tmp; } int main(void) { ... int num1 = 5; int num2 = 21; cout << "Before, num1 is " << num1 << " and num2 is " << num2 << endl; genericSwap( num1, num2 ); cout << "After, num1 is " << num1 << " and num2 is " << num2 << endl; char c1 = 'a'; char c2 = 'z'; cout << "Before, c1 is " << c1 << " and c2 is " << c2 << endl; genericSwap( c1, c2 ); cout << "After, c1 is " << c1 << " and c2 is " << c2 << endl; ... return( 0 ); } </pre> </div> <div class="related-name-format"> Related topics: </div> <div class="related-content"> <a href="typename.html">typename</a> </div> </div> </td> </tr> </table></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -