• c++多态实现之三 模板


    模板是C++支持参数化多态的工具,使用模板可以使用户为类或者函数声明一种一般模式,使得类中的某些数据成员或者成员函数的参数、返回值取得任意类型。

      模板是一种对类型进行参数化的工具;

      通常有两种形式:函数模板类模板

      函数模板针对仅参数类型不同的函数

      类模板针对仅数据成员成员函数类型不同的类。

      使用模板的目的就是能够让程序员编写与类型无关的代码。比如编写了一个交换两个整型int 类型的swap函数,这个函数就只能实现int 型,对double,字符这些类型无法实现,要实现这些类型的交换就要重新编写另一个swap函数。使用模板的目的就是要让这程序的实现与类型无关,比如一个swap模板函数,即可以实现int 型,又可以实现double型的交换。模板可以应用于函数和类。下面分别介绍。

      注意:模板的声明或定义只能在全局,命名空间或类范围内进行。即不能在局部范围,函数内进行,比如不能在main函数中声明或定义一个模板。

    具体的模板使用方法请参考专门将模板的书籍。

    这里举个模板使用例子:实现封装c++11的线程。

    #include <thread>
    #include <iostream>
    #include <list>
    
    using namespace std;
    
    class thead_group
    {
    private:
        thread_group(const thread_group&){} //禁用拷贝构造和赋值
        thread_group& operator=(const thread_group&){} 
    pubcli:
        template<typename... T>//可变参数列表模板
        void thread_create(T... func)
        {
               thread* p_thread = new thread(func...);
               vct_thread.push(p_thread);
        }
        void thread_join()
        {
             for(const auto &thrd : vct_threads)
            {
                  thrd->join();
            }
        }
    
    private:  
        list<thread*> vct_threads;
    }
    
    void func1()
    {
        cout << "this is func1" << endl;
    }    
    
    void func2(int a)
    {
        cout << "this is fun2, param : " << a << endl;  
    }
    
    int main(int argc, char** argv)
    {
        thread_group thrd;
        thrd.create_thread(func1);    
        thrd.create_thread(func2, 10);
        thrd.thread_join();
        return 0;
    }
           

    输出结果:this is func1       this is func2, param : 10

  • 相关阅读:
    BZOJ 2565 最长双回文串 (Manacher)
    BZOJ 3881 [COCI2015]Divljak (Trie图+Fail树+树链的并+树状数组维护dfs序)
    BZOJ 3530 [SDOI2014]数数 (Trie图/AC自动机+数位DP)
    BZOJ 1444 [JSOI2009]有趣的游戏 (Trie图/AC自动机+矩阵求逆)
    BZOJ 1195 [HNOI2006]最短母串 (Trie图+状压+bfs最短路)
    luogu P5289 [十二省联考2019]皮配
    luogu P5285 [十二省联考2019]骗分过样例
    luogu P5294 [HNOI2019]序列
    luogu P5292 [HNOI2019]校园旅行
    luogu P5284 [十二省联考2019]字符串问题
  • 原文地址:https://www.cnblogs.com/chengyuanchun/p/4375556.html
Copyright © 2020-2023  润新知