C + + function template review

Source: Internet
Author: User

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


Template <class t>
T Add (t one, T)
{
cout << "type:" << typeid (T). Name () << Endl;
return one + one; Function templates are compiled only when they are called, and some compilers compile at first compile time
}


int add (int one, int)
{
cout << "Custom int" << Endl;
return one + one;
}


Template <class T, class f>//function templates can not only accept data types, but also accept operation types
void Show (T T, F F)
{
F (t);
}
void Show_ (int temp)
{
cout << temp << Endl;
}


Template<class T1, Class t2>
Auto Temp1 (T1 t1, T2 T2)->decltype (T1+T2)//automatic type inference
{
return t1 + T2;
}


Template<class t>
void Temp2 (T t)
{
Decltype (t) D; Create a variable of the same type as T
}


int main ()
{
cout << Add (1.2, 1.2) << Endl;
cout << Add (1, 2) << Endl; If there is a custom function int add (int, int), the custom will be preferred, otherwise the function template will be used
cout << add<int> << Endl; If a function template is instantiated, the function template is used regardless of whether or not the custom function add


Show (1, Show_);
Show (1, [] (int i) {cout << i << "lambda" << Endl;}); You can pass a lambda expression as an action type to a function template


int a = 10;
Decltype (a) b = 3; The function of the decltype is to copy the data type


cout << Temp (1.2, 1) << Endl;
cout << Temp (1, 1.2) << Endl;


return 0;
}

C + + function template review

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.