C + + Template programming-chapter II-Function templates

Source: Internet
Author: User

Template is compiled two times

The book says that the template is compiled two times: Before the instantiation, check the template code itself, this good understanding is to check the template is not related to the code, the second compilation is instantiated in the time to see whether the type into the problem, such as the string is not division.

There is also a problem to be aware of: when the template is instantiated, the compiler will be able to see the definition of the template. The following code hangs because main.cpp contains max.h, but none of the implementations of Max

1 //max.h2Template<typename t>3 Max ... ..4 5 //Max.cpp6#include"max.h"7 .....8 9 //main.cppTen#include"max.h" One  A intMain () - { -Max1,2); the     ... -}


return type as a parameter

When a compiler instantiates a template, it cannot be inferred from the type of the return value to instantiate.

1 template<typename T1, TypeName t2>2 T1 convert (constinreturn Static_cast<t1> (in);} 3 4 convert<doubleint> (123//  good5 Convert (123//  noooooo!

Non-template functions are preferred

Hand-made (non-template function) and die-carved (template function) than, hand-made priority.

1#include <iostream>2 3 usingstd::cout;4 usingStd::endl;5 6 intMaxintAintb)7 {8cout <<"int max (int, int) is called."<<Endl;9     returna > B?a:b;Ten } One  ATemplate<typename t> -T Max (ConstT & A,ConstT &b) - { thecout <<"template<typename t> t max (const T &, const T &) is called."<<Endl; -     returna > B?a:b; - } -  + intMain () - { +cout << Max (1,2) << Endl;//non-parametric Max Acout << max<> (1,2) << Endl;//parametric Max at  -     return 0; -}


Today, this looks like, go to see the mathematical equation.

@2015/6/15

C + + Template programming-chapter II-Function templates

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.