码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-03-29 13:35:45      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

模板是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

 

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

标签:

原文地址:http://www.cnblogs.com/chengyuanchun/p/4375556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!