C + + Supplements--function templates

Source: Internet
Author: User

C + + Supplements--function templates

Preface

The core idea of generics is the separation of data and algorithms. Function templates are the basis of generic programming.

function Templates

The function template begins with template<arg_list> and Arg_list is a list of generic parameters.

1. Determining the number of generic parameters for a templateinstance One

Here is an addition function template that, when instantiated, we pass in the normal data type.

#include <iostream>using namespace Std;template<typename T1, typename T2>auto Add (T1 t1, T2 T2)->decltype (T1 + T2) {return t1 + t2;} int main () {cout << Add (12.3, N) << endl;cout << Add (12.3) << endl;cin.get (); return 0;}
Run


Example Two

We can also pass in the function type.

#include <iostream>using namespace Std;template<typename T, typename f>void exec (const T &t, F f) {F (t);} int main () {exec ("calc", System); Cin.get (); return 0;}
Run System ("Calc"); Open Calculator



2. Non-deterministic number of generic parameters for a template

#include <iostream> #include <cstdarg>using namespace std;//The function of this null parameter is used to recursively terminate void show () {}//parameter number is variable, Parameter types are also diverse template<typename T, TypeName ... Args>    //typename ... Args is a mutable type list void Show (T T, Args...args) {cout << t << ends;show (Args ...);} int main () {Show (1, 2, 3, 4); Show (' A ', ' B ', ' C ', ' d '); Cin.get (); return 0;}
Run






Directory of all content

    • CCPP Blog Directory




C + + Supplements--function templates

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.