C++泛型编程-参数决定类型
类型做参数是C++模板实现的主要形式。由此实现了类模板-->模板类-->实例的过程
当然除此之外也可以参考bitset的实现方式,参数决定类型的做法。
#includeusing namespace std; template <bool condition> void Func() { if(condition) cout<<"trueFunc"<<endl; else cout<<"falseFunc"<<endl; } //template template 64> //可以有默认参数 class MyBitSet { public: MyBitSet():pbits(new char[bitnu]){} ~MyBitSet() { if(pbits) delete pbits; } void dis() { cout<<"it's a "< " 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]:"< 0]<<"--"<<"bit[2]"< 2]<<endl; MyBitSet<> bit64; bit64.dis(); bit[53]=0x01; cout<<"bit[53]:"<<int(bit[53])<<endl; return 0; }