码迷,mamicode.com
首页 > 编程语言 > 详细

C++模板编程 - 第八章 深入模板基础

时间:2015-06-26 12:24:10      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

Member function templates CANNOT be virtual! On the contrary odinary member function templates can be virtual.

Linkage of Templates

1 // default
2 extern "C++" tempalte<typename T> void normal();
3 
4 // no - templates cannot have C linkage
5 extern "C" template<typename T> void invalid();

Function templates can have internal linkage.

1 // use keyword static to indicate internal linkage
2 template<typename T> static void internal();

Template Parameters

1. type parameter

1 // a template with one type parameter and one non-type parameter
2 template<typename, int> class SomeClass;

2. non-type parameter

A non-type parameter must have determined value during compile-time or link-time. Allowed are: integer/enumeration; pointer; reference

1 // actually these two are the same, array is converted to a pointer
2 template<int buf[5]> class SomeClass;
3 template<int * buf> class SomecClass;

3. template parameter

1 // a function template with a template parameter
2 // class is ok but union and struct are not
3 template<typename<typename X> class C>
4 void f(C<int> * p);

Interestingly, the parameter of the parameter (which is a template)  of the template cannot be used by the (outer) template.

1 template<template<typename T> class List>
2 class Node {
3     static T * storage;    // no! T is the parameter of the parameter
4     ... 
5 };

Default parameters

 1 #include<iostream>
 2 #include<typeinfo>
 3 #include<string>
 4 
 5 using namespace std;
 6 
 7 // you can specify default value for T2 only if you have done that
 8 // for the parameters after it
 9 template<typename T1, typename T2, typename T3=int>
10 class Triple;
11 
12 template<typename T1, typename T2=double, typename T3>
13 class Triple;
14 
15 template<typename T1=char, typename T2, typename T3>
16 class Triple;
17 
18 // definition
19 template<typename T1, typename T2, typename T3>
20 class Triple
21 {
22 public:
23     Triple()
24     {
25         T1 t1;
26         T2 t2;
27         T3 t3;
28         cout << typeid(t1).name() << endl;
29         cout << typeid(t2).name() << endl;
30         cout << typeid(t3).name() << endl;
31 
32     }
33 };
34 
35 int main()
36 {
37     Triple<> trio;
38     return 0;
39 }

Actual Parameters for a Template

SUBSTITUTION FAILURE IS NOT AN ERROR

1. Local classes and local enumerations cannot be real type parameters

2. Unamed classes and unamed enumerations cannot neither.

 

 

 

 

changelog:

2015/6/26 Start this page.

C++模板编程 - 第八章 深入模板基础

标签:

原文地址:http://www.cnblogs.com/ch3cooh/p/cpp_template_ch8.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!