easy conversion between two basic_string types...

J

Jim Kogler

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
 
V

Victor Bazarov

Jim said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top