Bits in einem Array als L-Value behandeln
-
Hi Leute.
Ich habe mir eine Klasse geschrieben, die ähnlich wie std::bitset eine Sammlung von Bits darstellt. Dazu habe ich auch den Index-Operator überladen. Allerdings kann ich den Rückgabewert des Indexoperators nicht als L-Value benutzen, da C++ ja minimal bytes adressieren kann. Also habe ich versucht, einen Wrapper dafür zu schreiben:class ref; class bitarray { unsigned int bits[5]; //hält 160 bits public: bool operator [] (int pos) const { return check_bit(pos); } ref operator [] (int pos) //Index Operator als L-Value { return ref(*this, pos); } bool check_bit(int pos) const { //... } void set_bit(int pos) { //... } }; class ref { bitarray* obj; int pos; public: bool operator = (bool b) { obj->set_bit(b); return b; } ref(bitarray& a, int b) : obj(&a), pos(b) {} operator bool() const { return obj->check_bit(pos); } }; int main() { bitarray a; a[4]=true; }Allerdings erhalte ich drei Fehlermeldungen, wenn ich versuche, das zu kompilieren:
15: error: return type 'struct ref' is incomplete 16: error: invalid use of undefined type 'struct ref' 1 : error: forward declaration of 'struct ref'Was mache ich falsch? Und vor Allem: Wie mache ich es richtig?
-
Nach einigem Rumprobieren habe ich das Programm zum Laufen gebracht. Wenn ich aber versuche, das Problem auf mein "richtiges" Projekt zu übertragen, bekomme ich einen Fehler:
template<unsigned int N> class bitarray; //forward declaration template<unsigned int N> class ref_bitarray { bitarray<N>* const obj; unsigned int bit; ref_bitarray(); public: ~ref_bitarray(); bool operator=(bool); ref_bitarray(bitarray<N>&, unsigned int); operator bool() const; }; template<unsigned int N> class bitarray { unsigned int bits [ N/32 ]; public: bool operator[](unsigned int pos) const { return check_bit(pos); } template<unsigned int T> ref_bitarray<N> operator[](unsigned int pos) //Index Operator als L-Value { return ref_bitarray<N>(*this, pos); } bool check_bit(unsigned int pos) const { //... } void set_bit (unsigned int pos, bool value) { //... } }; template<unsigned int N> ref_bitarray<N>::~ref_bitarray(){} template<unsigned int N> bool ref_bitarray<N>::operator=(bool b) { obj->set_bit(bit, b); return b; } template<unsigned int N> ref_bitarray<N>::ref_bitarray(bitarray<N>& a, unsigned int i) : obj(&a), bit(i) {} template<unsigned int N> ref_bitarray<N>::operator bool() const { return obj->check_bit(bit); } int main() { bitarray<64> a; a[4]=true; }78: error: non l-value in assignmentAber sollte das so nicht funktionieren? Wenn ich das ganze komplett ohne templates schreibe, kompiliert es ohne Fehlermeldungen...
-
Meinst Du nicht (N+31)/32 statt N/32 ?
Was soll denn das template<unsigned int T> beim operator[] ?