zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:

    bzoj3052: [wc2013]糖果公园
    莫队算法心得
    bzoj1104: [POI2007]洪水pow
    bzoj1102: [POI2007]山峰和山谷Grz
    bzoj1121: [POI2008]激光发射器SZK
    bzoj1113: [Poi2008]海报PLA
    bzoj1103: [POI2007]大都市meg
    bzoj1396: 识别子串
    bzoj3756: Pty的字符串
  • 原文地址:https://www.cnblogs.com/chengyuanchun/p/4375556.html
Copyright © 2011-2022 走看看