首页 > 编程语言 > 详细

C++泛型编程-扩展

时间:2019-10-30 20:39:30      阅读:66      评论:0      收藏:0      [点我收藏+]

类型做参数是C++模板实现的主要形式。由此实现了类模板-->模板类-->实例的过程

当然除此之外也可以参考bitset的实现方式,参数决定类型的做法。

#include <iostream>

using namespace std;

template <bool condition>
void Func()
{
    if(condition)
        cout<<"trueFunc"<<endl;
    else
        cout<<"falseFunc"<<endl;
}

//template <uint32_t bitnu>
template <uint32_t bitnu = 64> //可以有默认参数
class MyBitSet
{
public:
    MyBitSet():pbits(new char[bitnu]){}
    ~MyBitSet()
    {
        if(pbits)
            delete pbits;
    }
    void dis()
    {
        cout<<"it‘s a "<<bitnu<<" bit BitClass"<<endl;
    }
    char& operator[](uint32_t offset)
    {
        return pbits[offset];
    }
private:
    char *pbits;
};


int main(int argc, char *argv[])
{
    Func<true>();
    Func<false>();

    MyBitSet<32>bit;
    bit.dis();
    bit[0]= a;
    bit[2]= g;
    cout<<"bit[0]:"<<bit[0]<<"--"<<"bit[2]"<<bit[2]<<endl;
    MyBitSet<> bit64;
    bit64.dis();
    bit[53]=0x01;
    cout<<"bit[53]:"<<int(bit[53])<<endl;
    return 0;
}

 

C++泛型编程-扩展

原文:https://www.cnblogs.com/wangkeqin/p/11767418.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!