欣乐

The eagles are coming!

导航

第十六章 模板和泛型编程

 

 

 

 

 

code:

 

 

 

/*


第16章 模板与泛型编程 525
16.1 模板定义
16.2 实例化
16.3 模板编译模型
16.4 类模板成员
16.5 一个泛型句柄类
16.6 模板特化
16.7 重载与函数模板
小结


第16章 模板与泛型编程 525
16.1 模板定义 526
16.1.1 定义函数模板 526
16.1.2 定义类模板 528
16.1.3 模板形参 529
16.1.4 模板类型形参 531
16.1.5 非类型模板形参 533
16.1.6 编写泛型程序 534
16.2 实例化 535
16.2.1 模板实参推断 537
16.2.2 函数模板的显式实参 540
16.3 模板编译模型 542
16.4 类模板成员 545
16.4.1 类模板成员函数 548
16.4.2 非类型形参的模板实参 551
16.4.3 类模板中的友元声明 552
16.4.4 Queue和QueueItem的友元
声明 554
16.4.5 成员模板 556
16.4.6 完整的Queue类 558
16.4.7 类模板的static成员 559
16.5 一个泛型句柄类 560
16.5.1 定义句柄类 561
16.5.2 使用句柄 562
16.6 模板特化 564
16.6.1 函数模板的特化 565
16.6.2 类模板的特化 567
16.6.3 特化成员而不特化类 569
16.6.4 类模板的部分特化 570
16.7 重载与函数模板 570
小结 573
术语 574

*/



//第16章 模板与泛型编程

//16.1 模板定义 --------------------------------------------------------------------------------------------------------

 
#include <iostream>
#include <string>
using namespace std;

// returns 0 if the values are equal, -1 if v1 is smaller, 1 if v2 is smaller
int compare(const string &v1, const string &v2)
{
  if(v1 < v2)
    return  - 1;
  if(v2 < v1)
    return 1;
  return 0;
}

int compare(const double &v1, const double &v2)
{
  if(v1 < v2)
    return  - 1;
  if(v2 < v1)
    return 1;
  return 0;
}

int main()
{
  cout << compare("abc","def") << endl;
  cout << compare(3.14,3.1415) << endl;
  
  return 0;
}


// 函数模板 function template
#include <iostream>
#include <string>
using namespace std;

// implement strcmp-like generic compare function
// returns 0 if the values are equal, 1 if v1 is larger, -1 if v1 is smaller
template <typename T> int compare(const T &v1, const T &v2)
{
  if(v1<v2) return  - 1;
  if(v2<v1) return 1;
  return 0;
}

int main()
{
  cout << compare("abc","def") << endl;
  cout << compare(3.14,3.1415) << endl;
  
  return 0;
}



// in book
 
#include <iostream>
#include <string>
using namespace std;

// implement strcmp-like generic compare function
// returns 0 if the values are equal, 1 if v1 is larger, -1 if v1 is smaller
template <typename T> int compare(const T &v1, const T &v2)
{
  if(v1<v2) return  - 1;
  if(v2<v1) return 1;
  return 0;
}

int main()
{
  // T is int;
  // compiler instantiates int compare(const int&, const int&)
  cout << compare(1, 0) << endl;
  // T is string;
  // compiler instantiates int compare(const string&, const string&)
  string s1 = "hi", s2 = "world";
  cout << compare(s1, s2) << endl;
  
  return 0;
}



// inline
#include <iostream>
#include <string>
using namespace std;

// 声明
// ok: inline specifier follows template parameter list
  template <typename T> inline int compare(const T&, const T&);
// error: incorrect placement of inline specifier
//inline template <typename T> int compare(const T&, const T&);

// 定义
template <typename T> int compare(const T &v1, const T &v2)
{
  if(v1<v2) return  - 1;
  if(v2<v1) return 1;
  return 0;
}

int main()
{
  // T is int;
  // compiler instantiates int compare(const int&, const int&)
  cout << compare(1, 0) << endl;
  // T is string;
  // compiler instantiates int compare(const string&, const string&)
  string s1 = "hi", s2 = "world";
  cout << compare(s1, s2) << endl;
  
  return 0;
}


// 类模板接口
template <class Type> class Queue
{
  public:
    Queue(); // default constructor
    Type &front(); // return element from head of Queue
    const Type &front()const;
    void push(const Type &); // add element to back of Queue
    void pop(); // remove element from head of Queue
    bool empty()const; // true if no elements in the Queue
  private:
    // ...
};


// 使用类模板
Queue<int> qi;                 // Queue that holds ints
Queue< vector<double> > qc;    // Queue that holds vectors of doubles
Queue<string> qs;              // Queue that holds strings



// 非类型模板形参 
#include <iostream>
#include <string>
using namespace std;

// initialize elements of an array to zero
template <class T, size_t N> void array_init(T (&parm)[N])
{
    for(size_t i = 0; i != N; ++i)
    {
        parm[i] = 0;
    }
}

int main()
{
  int x[42];
  double y[10];
  array_init(x); // instantiates array_init(int(&)[42]
  array_init(y); // instantiates array_init(double(&)[10]
}


/*
编写泛型代码的两个重要原则:
    The parameters to the template are const references.
    模板的形参是 const 引用。
    The tests in the body use only < comparisons.
    函数体中的测试只用 < 比较。
*/



//16.2 实例化 --------------------------------------------------------------------------------------------------------


// 实参类型不同,将产生编译错误 
#include <iostream>
#include <string>
using namespace std;

template <typename T> int compare(const T &v1, const T &v2)
{
  if(v1<v2) return  - 1;
  if(v2<v1) return 1;
  return 0;
}

int main()
{
  short si;
  // error: cannot instantiate compare(short, int)
  // must be: compare(short, short) or
  // compare(int, int)
  compare(si, 1024);
  return 0;
}




// 在函数模板中,定义两个形参类型,就可以了 
#include <iostream>
#include <string>
using namespace std;

// 定义成两个类型
template <typename T, typename B> int compare(const T &v1, const B &v2)
{
  if(v1<v2) return  - 1;
  if(v2<v1) return 1;
  return 0;
}

int main()
{
  short si;
  // error: cannot instantiate compare(short, int)
  // must be: compare(short, short) or
  // compare(int, int)
  compare(si, 1024);
  return 0;
}



template <typename T> T fobj(T, T); // arguments are copied
template <typename T> T fref(const T &, const T &); // reference arguments
string s1("a value");
const string s2("another value");
fobj(s1, s2); // ok: calls f(string, string), const is ignored
fref(s1, s2); // ok: non const object s1 converted to const reference
int a[10], b[42];
fobj(a, b); // ok: calls f(int*, int*)
fref(a, b); // error: array types don't match; arguments aren't converted to pointers



// in book 
#include <iostream>
#include <string>
using namespace std;

template <class Type> Type sum(const Type &op1, int op2)
{
    return op1 + op2;
} 

int main()
{
  double d = 3.14;
  string s1("hiya"), s2(" world");
  sum(1024, d); // ok: instantiates sum(int, int), converts d to int
  sum(1.4, d); // ok: instantiates sum(double, int), converts d to int
  // sum(s1, s2); // error: s2 cannot be converted to int
}


// 函数指针
template <typename T> int compare(const T&, const T&);
// pf1 points to the instantiation int compare (const int&, const int&)
int (*pf1) (const int&, const int&) = compare;



 
#include <iostream>
#include <string>
using namespace std;

template <class T1, class T2, class T3> T1 sum(const T2 &i, const T3 &j)
{
  return i+j;
}

int main()
{
  long val3 = sum<long>(2, 3);
  cout << val3 << endl;
  cout << sizeof(val3) << endl;
  return 0;
}



//16.3 模板编译模型 --------------------------------------------------------------------------------------------------------


//16.4 类模板成员 --------------------------------------------------------------------------------------------------------


#include <iostream>
#include <string>
using namespace std;

template <class Type> class QueueItem
{
    // private class: no public section
    QueueItem(const Type &t): item(t), next(0){}
    Type item; // value stored in this element
    QueueItem *next; // pointer to next element in the Queue
};

template <class Type> class Queue
{
  public:
    // empty Queue
    Queue(): head(0), tail(0){}
    // copy control to manage pointers to QueueItems in the Queue
    Queue(const Queue &Q): head(0), tail(0)
    {
        copy_elems(Q);
    } 
    Queue &operator = (const Queue &);
    ~Queue()
    {
        destroy();
    }
    // return element from head of Queue
    // unchecked operation: front on an empty Queue is undefined
    Type &front()
    {
        return head->item;
    }
    const Type &front()const
    {
        return head->item;
    }
    void push(const Type &); // add element to back of Queue
    void pop(); // remove element from head of Queue
    bool empty()const
    {
        // true if no elements in the Queue
        return head == 0;
    }
  private:
    QueueItem < Type >  *head; // pointer to first element in Queue
    QueueItem < Type >  *tail; // pointer to last element in Queue
    // utility functions used by copy constructor, assignment, and destructor
    void destroy(); // delete all the elements
    void copy_elems(const Queue &); // copy elements from parameter
};

template <class Type> void Queue<Type>::destroy()
{
    while(!empty())
      pop();
} 

template <class Type> void Queue<Type>::pop()
{
    // pop is unchecked: Popping off an empty Queue is undefined
    QueueItem<Type>  *p = head; // keep pointer to head so we can delete it
    head = head->next; // head now points to next element
    delete p; // delete old head element
} 

template <class Type> void Queue<Type>::push(const Type &val)
{
    // allocate a new QueueItem object
    QueueItem<Type>  *pt = new QueueItem<Type> (val);
    // put item onto existing queue
    if(empty())
      head = tail = pt;
    // the queue now has only one element
    else
    {
        tail->next = pt; // add new element to end of the queue
        tail = pt;
    }
}

template <class Type> void Queue<Type>::copy_elems(const Queue &orig)
{
    // copy elements from orig into this Queue
    // loop stops when pt == 0, which happens when we reach orig.tail
    for(QueueItem<Type>  *pt = orig.head; pt; pt = pt->next)
      push(pt->item);
    // copy the element
} 

int main()
{
  return 0;
}

//  后面部分先略。

//16.5 一个泛型句柄类 --------------------------------------------------------------------------------------------------------

//16.6 模板特化 --------------------------------------------------------------------------------------------------------

//16.7 重载与函数模板 --------------------------------------------------------------------------------------------------------


// 后面两章,纯粹浏览,代码木有,或者先略。。。


141118

 

 

 

 

 

 

TOP

 

posted on 2014-11-10 19:56  欣乐  阅读(135)  评论(0编辑  收藏  举报