C++ Primer 学习笔记_75_模板与泛型编程 --模板定义(二)

2014-11-24 12:59:05 · 作者: · 浏览: 1

2、使用模板形参名字的限制

用作模板形参的名字不能在模板内部重用:

template 
  
   
T calc(const T &a,const T &b)
{
    typedef double T;   //Error

    T tmp = a;
    //...
    return tmp;
}

  

这一限制还意味着模板形参的名字只能在同一模板形参表中使用一次:

template 
  
    T calc(const T &a,const T &b);	//Error

  

正如可以重用函数形参名字一样,模板形参的名字也能在不同模板中重用:

template 
  
    T calc(const T &a,const T &b);

template 
   
     int compare(const T &,const T&); //OK 
   
  

3、模板声明

像其他任意函数或类一样,对于模板可以只声明而不定义声明必须指出函数或类是一个模板:

template 
  
   
int compare(const T &,const T&);

  

同一模板的声明和定义中,模板形参的名字不必相同:

template 
  
   
T calc(const T &,const T &);

template 
   
     U calc(const U&,const U&); template 
    
      Type calc(const Type &,const Type &); 
    
   
  

每个模板类型形参前面必须带上关键字class或typename,每个非类型形参前面必须带上类型名字,省略关键字或类型说明符是错误的:

template
  
   
T calc(const T &,const U &);	//Error

template
   
     T calc(const T &,const U &); //OK 
   
  

//P531 习题16.9
template 
  
   
Type find(Type begin,Type end,const T &val)
{
    while (begin != end)
    {
        if (*begin == val)
        {
            return begin;
        }
        ++ begin;
    }

    return end;
}

int main()
{
    int ia[] = {01,1,1,999,2,3,2,34,4,3,4};

    int *p;
    if ((p = find(ia,ia+sizeof(ia)/sizeof(*ia),999)) != ia + sizeof(ia)/sizeof(*ia))
    {
        cout << *p << endl;
    }
    else
    {
        cout << "Not Found!" << endl;
    }

    vector
   
     iVec(ia,ia + sizeof(ia)/sizeof(*ia)); vector
    
     ::iterator iter; if ((iter = find(iVec.begin(),iVec.end(),888)) != iVec.end()) { cout << *iter << endl; } else { cout << "Not Found!" << endl; } ifstream inFile("input"); vector
     
       strVec; string val; while (inFile >> val) { strVec.push_back(val); } vector
      
       ::iterator it; if ((it = find(strVec.begin(),strVec.end(),"hello")) != strVec.end()) { cout << *it << endl; } else { cout << "Not Found!" << endl; } }