|
Hi,
This is a question about declaring a signed 8bit numeric type in C++ that prints like a numeric variable and not like a char variable. I would like to declare a type with name 'byte' which represents 8bit numeric values. Of course C++ has char with the right size. So I tried
------
typedef char byte;
------
This is fine, until I tried
---------
byte b = 1;
cout << b;
---------
This (as expected) does not output '1' (as I would like), but rather the char with ascii code 1. Since I would prefer my numeric types to print as their decimal value (like int, doulbe, etc.), I tried
--------
typedef char byte;
std::ostream &operator<<(std::ostream &os, const byte &b) {
os << (int)b;
return os;
}
-------
Now
--------
char b=62;
cout << b;
-------
prints '62' and not 'A'. It seems that typedef is simply aliasing and not actually creating a new type. My next attempt is to create a new type which just wraps char
---------
class byte {
char v;
public:
byte() : v() { }
byte(const byte &w) : v(w.v) { }
byte(const char &w) : v(w) { }
byte &operator=(const byte &w) { v = w.v; return *this; }
byte &operator=(const char &w) { v = w; return *this; }
operator char() { return v; }
friend std::ostream &operator<<(std::ostream &, const byte &);
friend std::istream &operator>>(std::istream &, byte &);
};
std::ostream &operator<<(std::ostream &os, const byte &b) {
os << (int)b.v;
return os;
}
------------
This works fine, except when compiling with g++ (GCC) 4.1.2 20071124 (Red Hat 4.1.2-42)
------
byte b = 0;
b++;
-----
produces:
error: no 'operator++(int)' declared for postfix '++', trying prefix operator instead
error: no match for 'operator++' in '++b'
This is rather odd because
------
byte b = 0;
b = b + 1;
-----
compiles fine (the conversion to unsigned char is called as intended).
So it seems like I have to declare ++, --, +=, .... At this point I gave up on this attempt because it seemed to me that the solution is already going out of hand for what I wanted originally.
Is there an elegant solution to this?
Thanks,
Vladimir
|