This is one that I've never quite "got".
How do I assign a derived class type to its base class type?
Concretely:
I'm making myself a
std::basic_string<>-derived class that overloads all the comparison functions to work case-insensitively. In all other respects it should be identical to a normal string --it stores and writes and reads and quuxes its data with case-sensitivity just like the base class --because it inherits all that behavior.
(Aside: The reason I didn't just play with the
std::char_traits<> is because doing so invalidates use of the class with things like
cout etc.)
Now I know that the instant answer is: because a
derived class is
different than a base class --otherwise they would be the same class...
But in this case, I don't care. If I assign a
basic_cistring<> to a
basic_string<> it will (obviously) loose all its case-insensitive comparison powers. That is correct.
BUT, the problem is I just don't quite understand how to initialize a base reference with the derived reference.
I've tried this:
1 2 3 4 5 6 7 8 9 10
|
template <...>
struct base_cistring: public std::basic_string <...>
{
...
operator std::basic_string <...> ()
{
return std::basic_string <...> ( this->c_str(), this->length() );
}
...
};
|
which compiles fine, but doesn't seem to get used...
I've also tried overloading the assignment operator:
1 2 3 4 5
|
template <...> inline
std::basic_string <...> operator = ( const basic_cistring <...> & source )
{
...
}
|
but the compiler complains to me that this must be a non-static member function (even though the assignment is
not to the derived class!).
Alas! I'm over my head with this issue. Help!
:-(
[edit] fixed typo
[edit2] Man, having written that, I think I forgot an argument to the = operator. Let me fix that and I'll post back if it works..
[edit3] Argh. Nope, problem remains.
[final edit]
Well, it seems that you
can assign to the base type (I thought you could!), but I also needed to override all the class constructors...
<grumble>
:-)