C++泛型编程-扩展

类型做参数是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;
}

猜你喜欢

转载自www.cnblogs.com/wangkeqin/p/11767418.html
今日推荐