Template and model programming (non-type template parameters), array Initialization

Source: Internet
Author: User

The template parameters do not have to be all types.

When a function is called, non-type parameters are replaced by values. The value type is specified in the template parameters table.

E.g .:

# Include <iostream> using namespace STD; typedef int t; Template <typename T> // <class T> inline t subtract (T T1, t T2) {return t1-t2 ;} template <class T> class mycls {public: T T1; t gett () {return T1 ;}; // (non-type template parameters) // initialize the array template <typename T, size_t n> void arr_init (T (& ARR) [N]) {for (INT I = 0; I <n; ++ I) {arr [I] = 0 ;}// calculation and template <typename T, size_t n> T arr_sum (T (& ARR) [N]) {t Sum = 0; for (INT I = 0; I <n; ++ I) {sum + = arr [I];} return sum;} int main () {int arr [10]; for (INT I = 0; I <10; ++ I) {cout <arr [I] <"," ;}cout <Endl; arr_init (ARR ); for (INT I = 0; I <10; ++ I) {cout <arr [I] <"," ;}cout <Endl; // After the value is assigned, for (INT I = 0; I <10; ++ I) {arr [I] = I + 1;} int result = arr_sum (ARR ); cout <result <Endl;/* int A = subtract (1, 2); cout <A <", double:" <subtract (1.1f, 2.2f) <Endl; mycls <int> mc1; mc1.t1 = 123; cout <mc1.gett () <Endl; mycls <double> MC2; mc2.t1 = 123.12345; cout <mc2.gett () <Endl; */return 0 ;}

 

 

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.