easy conversion between two basic_string types...



 DEVELOP > c-Plus-Plus > easy conversion between two basic_string types...

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

 
Topic: DEVELOP > c-Plus-Plus
User: "Jim Kogler"
Date: 02 Aug 2004 10:34:33 AM
Object: easy conversion between two basic_string types...
I have created a new string type with a memory pool allocator. Lets
presume the allocator works, my type is defined as:
typedef std::basic_string<char, std::char_traits<char>,
pool_allocator<char> > NewStr;
This is the same as std::string except with a different allocator,
right?
I want to be able to implicitly convert from std::string to NewStr
like:
std::string a("hi");
NewStr b("there");
a = b;
or
b = a;
which doesnt work, becasue they are different types. So my question
is, if i wanted to do this:
class MyString : public NewStr
{ public:
MyString &operator=(const std::string &other)
{
// what is the best way to do this?
*this = other.c_str(); /// doesnt look good...
return *this;
}
of course the same question could apply to the copyCtor too...
and, to go the other way, should i do the same thing for the
operator const std::string&() {...} method?
Is there a better way to create my type?
Jim
.

User: "Victor Bazarov"

Title: Re: easy conversion between two basic_string types... 02 Aug 2004 10:48:39 AM
Jim Kogler wrote:

I have created a new string type with a memory pool allocator. Lets
presume the allocator works, my type is defined as:


typedef std::basic_string<char, std::char_traits<char>,
pool_allocator<char> > NewStr;

This is the same as std::string except with a different allocator,
right?

Right. It makes it a totally different, unrelated type, nonetheless.


I want to be able to implicitly convert from std::string to NewStr
like:

std::string a("hi");
NewStr b("there");
a = b;

or
b = a;

which doesnt work, becasue they are different types. So my question
is, if i wanted to do this:

class MyString : public NewStr
{ public:
MyString &operator=(const std::string &other)
{
// what is the best way to do this?
*this = other.c_str(); /// doesnt look good...

Probably something like
this->assign(other.begin(), other.end());

return *this;
}

of course the same question could apply to the copyCtor too...

You may use 'assign' there too.


and, to go the other way, should i do the same thing for the

operator const std::string&() {...} method?

No. What would it be a reference to? You can only return an object
from that, and not a reference:
operator std::string() const {
return std::string(this->begin(), this->end());
}


Is there a better way to create my type?

Not if you want your implicit conversions.
Victor
.


  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER