`
asda1sdas
  • 浏览: 2638 次
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

templates

    博客分类:
  • C++
 
阅读更多
1.所谓 funtion templates 是指既由参数化手段表现一整个族群的funtion
1.1 定义 Template
  
    template<class T>
    inline T const& max(T const& a,T const & b)
    {
        return a > b ? a:b;
    }

1.2 template 使用
  
    int main()
    {
      int i = 24;
      std::cout<<"max(7 ,i)"<< ::max(7,i) <<std::endl;
      double f1 = 2.4, f2 = -1.4;
      std::cout<<"max(f1 ,f2)"<< ::max(f1,f2) <<std::endl;
      std::string str1 = "wpl", str2 ="wpl@@@";
      std::cout<<"max(str1 ,str2)"<< ::max(str1,str2) <<std::endl;
    }
    说明:1.三次的max调用分别使用了模板的不同的实体,
          2. max调用前的(::) 确保调用的是我们在全局命名空间定义的max。
          3.使用funtion template 被调用,就会自动引发实例化过程,没必要个别申请实例化。

2. class template
2.1 声明 class template

    template<class T,.....> //此处可以class T 也可以为正常的 int char等等
    class stack{
     private:
          std::vector<T> elems; //元素
     public:
          void push(T const& elem);
          void pop();
          T top() const;
          bool empty() const{
              return elems.empty();
           }
    }
   
    //类声明完了,成员还是的定义
   
    template <class T>
    void stack<T>::push(T const& elem) {
           elems.push_back(elem);
    }

    template <class T>
    void stack<T>::pop(){
     
      if(!elems.empty())
      elems.pop_back();
    }

    说明:1.声明时加 template<class T, .......>,
          2.无论何时以这个类声明变量和函数是都要使用stack<T>::.
2.2 使用 class template
   void main() {
      stack<int>  intstack;
      stack<std::string>  stringstack;
   }
3. 模板特化
3.1 template<> stack<int>(int const&a, int const&b);

4.非类型类模板参数。 tempplate< class T,int MAXNUM>
   说明:非类型模板参数通常为常量整数或指针。 
5. this
   template<class T>
   class base{
    public:
       void exit();
   }

   template< class T>
   class Derivdd:public base<T>
   {
      public:
         void foo()
         {
           exit(); //不会调用基类的exit,如要调用基类要是修改为this->exit();
                   //或者base<T>::
          }
   }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics