zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    74.QT窗口实现类的封装
    73,QT指针数组实战(指针数组与数组指针)
    72.函数模板指针与类函数模板的绑定
    71.lambda表达式的递归
    C++ new delete(一)
    ios之@class
    xcode菜单栏
    ios 自定义delegate(一)
    strong&weak
    TCP/UDP
  • 原文地址:https://www.cnblogs.com/wangkeqin/p/11767418.html
Copyright © 2011-2022 走看看