ostream operator overloading for unsigned char in C++
Given:
typedef struct { char val[SOME_FIXED_SIZE]; } AString;
typedef struct { unsigned char val[SOME_FIXED_SIZE]; } BString;
I want to add ostream operator <<
available for AString
and BString
.
std::ostream & operator<<(std::ostream &out, const AString &str)
{
out.write(str.val, SOME_FIXED_SIZE);
return out;
}
If I do the same for BString
, the compiler complains about invalid conversion from 'const unsigned char*' to 'const char*'
. The ostream.write
does not have const unsigned char*
as argument.
It seems <<
itself accepts the const unsigned char
, so I try something like this
std::ostream & operator<<(std::ostream &out, const BString &str)
{
for (int i=0; i<SOME_FIXED_SIZE; i++)
{
out<<str.val[i];
}
return out;
}
Can someone tell me if this is right/good practice or th开发者_运维技巧ere are some better ways? welcome any comments!
The simplest and cleanest solution is to create an std::string
, e.g.:
out << std::string(str.val, str.val + sizeof(str.val));
However, the question is: do you want formatted or unformatted output?
For unformatted output, as ugly as it is, I'd just use a
reinterpret_cast
.
Have you thought about casting it to char*
:
std::ostream & operator<<(std::ostream &out, const BString &str)
{
out.write(reinterpret_cast<char*>(str.val), sizeof(str.val));
return out;
}
精彩评论