zoukankan      html  css  js  c++  java
  • c++之模板

    1. 函数模板
    
    普通函数
    
    void Swap(int &, int &);
    
    模板函数
    
    template <typename T>
    
    void Swap(T &, T &);
    
    显示具体化,下面两个等价
    
    template<> void Swap<int>(int &, int &);
    
    template<> void Swap(int &, int &);
    
    注意:具体化将覆盖模板函数,普通函数将覆盖具体化和模板函数。
    
     
    
    显式实例化函数
    
    template void Swap<int>(int &, int &);
    
    注意:在同一编程单元中使用同一种类型的显式实例和显示具体化将出错。
    
     
    
    2.类模板
    
    多参数类型
    
    template <typename T1, typename T2>
    
    class Pair
    
    {
    
    private:
    
      T1 a;
    
      T2 b;
    
    };
    
     
    
    默认类型模板参数
    
    template <typename T1, typename T2 = int>
    
    class Topo
    
    {};
    
    类模板类型参数提供默认值,但不能为函数模板参数提供默认值。
    
     
    
    模板具体化
    
    1.隐式实例化
    
    A<int> *temp; 不会生成类的隐式实例化
    
    temp = new A<int>; 生成类的定义
    
     
    
    2.显式实例化
    
    声明必须位于模板定义所在的名称空间中,
    
    template class A<string, 100>;
    
     
    
    3.显式具体化
    
    通用的模板
    
    template <typename T>
    
    class SortedArray
    
    {};
    
    具体化
    
    template <> class SortedArray<char *>
    
    {};
    
     
    
    4.部分具体化
    
    普通模板
    
    template <typename T1, typename T2>
    
    class Topo
    
    {};
    
    部分具体化
    
    template <typename T1> class Topo<T1, int> {};
    
     
    
    3.模板类和友员
    
    非模板友员
    
    template <typename T>
    
    class hasFriend
    
    {
    
      friend void counts();
    
      friend void report(HasFriend<T>&);
    
    }
    
    模板类的约束模板友元函数
    
    template <typename T> void counts();
    
    template <typename T> void report(T &);
    
     
    
    template <typename TT>
    
    class hasFriend
    
    {
    
      friend void counts<TT>();
    
      friend void report<>(HasFriend<TT>&);
    
    }
    
    模板类的非约束模板友元函数
    
    template <typename T>
    
    class ManyFriend
    
    {
    
      template <typename C, typename D> friend void show2(C &, D &);
    
    };
  • 相关阅读:
    [一个64位操作系统的设计与实现] 3.1 Func_GetFATEntry疑惑
    【参考】 实现X86_64架构下的BootLoader(二)文件系统
    LBA和CHS转换(转)
    Grafana 重置admin密码
    linux-source: not found ubuntu执行脚本报错
    Hbase学习
    高并发理解
    Linux下安装Artemis
    SpringInAction 第八章 发送异步消息
    SpringInAction 六七章总结
  • 原文地址:https://www.cnblogs.com/kaishan1990/p/5468811.html
Copyright © 2011-2022 走看看