I'm trying to design a buffer class, which contains a block of unsigned char. The std::basic_string<unsigned char> seems exactly what I need, but here's the problem, when I append data to the buffer, for convenience, I need the append function can take both char* and unsigned char*, for example:
Then I derived the basic_string, and extend the append function:
1 2 3 4 5 6
struct buffer : public basic_string<uchar> {
buffer& append(constchar* s, int size) {
append((uchar*)s, size);
return *this;
}
};
but it also doesn't work, compile error: append cannot convert uchar* to const char*
seems after the deriving, the other append() functions from basic_string are gone
why is that and how to fix?
I think the problem is that when it finds a append function in the base class it will not go on to look for it in the subclasses. You can fix this by using using.
1 2 3 4 5 6 7
struct buffer : public basic_string<uchar> {
buffer& append(constchar* s, int size) {
append((uchar*)s, size);
return *this;
}
using basic_string<uchar>::append;
};
any better solution? I think it's better not to have a new function, because I will have to write some other add() wrappers for the other append() functions.
std::basic_string is not polymorphic, you're not supposed to derive from it to start with. But even if it were,
design a buffer class, which contains a block of unsigned char
This design pattern is called "composition". The buffer class should have vector<unsigned char> or basic_string<unsigned char> or some other 'block of unsigned char' as a data member.