Casting from a string

  • Thread starter Alexander Dong Back Kim
  • Start date
A

Alexander Dong Back Kim

Dear members,

I'm trying to implement a complex number (not that complex =P) class
and make it compatible with string.
The following codes are brief case of what I'm trying to do...

class Complex
{
protected :
int _value;

operator string (void)
{
stringstream ss;
ss << this->_value;

string str;

if (ss >> str)
return str;
else
return "";
}

//? friend string::eek:perator Complex (void);
};

As you can see the codes, the class can convert the value (which is
"int" in this case... I'm not talking about atoi or itoa here...).
However, I have no idea who I can overload from string to Complex
function...

Any suggestion or idea?

best regards,
Alex Kim
 
O

Obnoxious User

Dear members,

I'm trying to implement a complex number (not that complex =P) class and
make it compatible with string.
The following codes are brief case of what I'm trying to do...

class Complex
{
protected :
int _value;

operator string (void)
{
stringstream ss;
ss << this->_value;

string str;

if (ss >> str)
return str;
else
return "";
}

//? friend string::eek:perator Complex (void);
};

As you can see the codes, the class can convert the value (which is
"int" in this case... I'm not talking about atoi or itoa here...).
However, I have no idea who I can overload from string to Complex
function...

Any suggestion or idea?

Complex::Complex(std::string const &);
void Complex::eek:perator=(std::string const &);
 
T

Triple-DES

Dear members,

I'm trying to implement a complex number (not that complex =P) class
and make it compatible with string.
The following codes are brief case of what I'm trying to do...

class Complex
{
protected :
    int _value;

    operator string (void)
    {
        stringstream ss;
        ss << this->_value;

        string str;

        if (ss >> str)
            return str;
        else
            return "";
    }

    //? friend string::eek:perator Complex (void);

};

As you can see the codes, the class can convert the value (which is
"int" in this case... I'm not talking about atoi or itoa here...).
However, I have no idea who I can overload from string to Complex
function...

Any suggestion or idea?

Do you mean conversion from string to complex?
In that case a constructor will do:

/* explicit */ Complex(const std::string& str)
{
// ...
}

Consider declaring this constructor explicit, or you may get some
unintended conversions from string to Complex.

DP
 
A

Alexander Dong Back Kim

Do you mean conversion from string to complex?
In that case a constructor will do:

/* explicit */ Complex(const std::string& str)
{
  // ...

}

Consider declaring this constructor explicit, or you may get some
unintended conversions from string to Complex.

DP

Excellent!!!!!

Thanks DP and OU =)
 
A

Alexander Dong Back Kim

Do you mean conversion from string to complex?
In that case a constructor will do:

/* explicit */ Complex(const std::string& str)
{
  // ...

}

Consider declaring this constructor explicit, or you may get some
unintended conversions from string to Complex.

DP

Dear Den,

Just one question. What do you mean by "unintended conversions"? Could
you explain me bit more detail like when it can happen and so on? I
appreciate that. Thank you very much.

regards,
Alex Kim
 
A

Alexander Dong Back Kim

Dear Den,

Just one question. What do you mean by "unintended conversions"? Could
you explain me bit more detail like when it can happen and so on? I
appreciate that. Thank you very much.

regards,
Alex Kim

Dear members,

As Den and Obnoxious suggested, I added an operator overloading in the
complex class.

class Complex
{
protected :
int _value;

Complex();
~Complex();
Complex(string const & str);
operator=(string const & str);
operator=(int32_t v);

operator string (void)
{
stringstream ss;
ss << this->_value;

string str;

if (ss >> str)
return str;
else
return "";
}


};

Now I added another operator "operator=(int32_t v);". I'm using visual
c++ 6.0 and it now complains about ambigous declaration when I use the
class like the following.

Complex a, b, c;
a = "100"; // Compiler doesn't complain and works fine!
b = 10; // This is also works fine!!!
// BUT!!!
c = 0; // THIS IS THE PROBLEM LINK!!!

Why "c = 0;" creates the error message? Is it because the compiler
doesn't know whether "0" is integer or NULL or even boolean?? Is there
any way to trick compiler accept this "0" as integer "0"?

best regards,
Alex Kim
 
J

James Kanze

I'm trying to implement a complex number (not that complex =P)
class and make it compatible with string.

What do you mean by compatible here? Complex numbers and
strings are orthogonal, and should be completely independent of
one another.
 
T

Thomas J. Gritzan

Alexander said:
As Den and Obnoxious suggested, I added an operator overloading in the
complex class.

class Complex
{
protected :
int _value;

Complex();
~Complex();
Complex(string const & str);
operator=(string const & str);
operator=(int32_t v);

What return value type does your operator= functions have?
operator string (void)
{
stringstream ss;
ss << this->_value;

string str;

if (ss >> str)
return str;
else
return "";

Why not simpler?
return ss.str();
}


};

Now I added another operator "operator=(int32_t v);". I'm using visual
c++ 6.0 and it now complains about ambigous declaration when I use the
class like the following.

Who forces you to use the old Visual C++ 6.0?
Complex a, b, c;
a = "100"; // Compiler doesn't complain and works fine!
b = 10; // This is also works fine!!!
// BUT!!!
c = 0; // THIS IS THE PROBLEM LINK!!!

Why "c = 0;" creates the error message? Is it because the compiler
doesn't know whether "0" is integer or NULL or even boolean?? Is there
any way to trick compiler accept this "0" as integer "0"?

What is "the error message"? Error messages contain information which is
useful in finding errors. Don't you want to tell us the message?
 
A

Alexander Dong Back Kim

What do you mean by compatible here? Complex numbers and
strings are orthogonal, and should be completely independent of
one another.

--
James Kanze (GABI Software) email:[email protected]
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Dear James,

First of all, it is honor to have your comment in this thread =)
The main reason I want to make the "complex" class cast-able with
std::string is I want to convert into a XML file format. For example,

If I have three instance of the class in a vector or some container
class...

vector<Complex> vComplex;
Complex a, b, c;
a = 10;
b = "100";
c = 0;

vComplex.push_back(a);
vComplex.push_back(b);
vComplex.push_back(c);

SaveToXML(vComplex); // Saving function that generates an XML file

....

I expect the XML look something like...

<Container>
<Complex> "10" </Complex>
<Complex> "100" </Complex>
<Compelx> "0" </Complex>
</Container>

In order to do this, in my opinion, std::string compatibility would be
the thing really nice to have for further string-related operations.
I'm sorry if my explanation is not clear enough. If you think my
approach is wrong or you think there are other approaches for doing
this kind of thing, please feel absolutely free to tell and let me
know about them. =)

regards,
Alex Kim
 
A

Alexander Dong Back Kim

What return value type does your operator= functions have?
I think I should've use "Complex & operator=" =) Thanks for that!
Why not simpler?
return ss.str();

That's a good suggestion =)
Who forces you to use the old Visual C++ 6.0?

Myself =) Since it seems you are wondering about my work, I'm just
playing around with Visual C++ 6.0 thesedays. When I solve this
problem then I will move on to Visual C++.NET... although I'm mainly
use GCC =)
What is "the error message"? Error messages contain information which is
useful in finding errors. Don't you want to tell us the message?

Thanks Thomas =)
 
A

Alexander Dong Back Kim

What return value type does your operator= functions have?




Why not simpler?
return ss.str();


Who forces you to use the old Visual C++ 6.0?



What is "the error message"? Error messages contain information which is
useful in finding errors. Don't you want to tell us the message?

Oh I missed a question. I'm sorry I can't remember the error code
number but it was somethign like "operator= ambiguous"

cheers,
Alex Kim
 
T

Thomas J. Gritzan

Alexander said:
Myself =) Since it seems you are wondering about my work, I'm just
playing around with Visual C++ 6.0 thesedays. When I solve this
problem then I will move on to Visual C++.NET... although I'm mainly
use GCC =)

You are aware that Visual C++ 6.0 is 10 years old now and has many known
bugs.
Visual C++.NET 2003, which is Visual C++ 7.1, and newer versions, have
much improved compatibility with the C++ standard and can compile to
native code, too (that is, not .NET binarys).
Thanks Thomas =)

You're welcome.
 
A

Alexander Dong Back Kim

You are aware that Visual C++ 6.0 is 10 years old now and has many known
bugs.
Visual C++.NET 2003, which is Visual C++ 7.1, and newer versions, have
much improved compatibility with the C++ standard and can compile to
native code, too (that is, not .NET binarys).


You're welcome.

That's a good point =) I remember I was using Visual C++ 5.x as my
learning tool in 1997. When VC++ 6.0 came out, I was fascinated by
"auto completion" =P Time flies! I can't believe it's been already
over 10 years =) By the way, I think you're right. I don't need to
spend some time for Visual C++ 6.0 anymore since .NET Framework's
version is already reached over 3.x or something.

I guess what I'm doing is like "using Turbo C++ in 2000". =P

regards,
Alex Kim
 
T

Thomas J. Gritzan

Alexander said:
That's a good point =) I remember I was using Visual C++ 5.x as my
learning tool in 1997. When VC++ 6.0 came out, I was fascinated by
"auto completion" =P Time flies! I can't believe it's been already
over 10 years =) By the way, I think you're right. I don't need to
spend some time for Visual C++ 6.0 anymore since .NET Framework's
version is already reached over 3.x or something.

You don't need .NET framework. Visual C++ 8.0 can compile both to native
code like VC++6.0 and to .NET assemblys. Throw away VC++6.0 and use
VC++8.0 to compile the same code.
The newest VC++ is free to download as express version.

You could even use a Windows port of GCC.
I guess what I'm doing is like "using Turbo C++ in 2000". =P

Yeah, like using Windows 98 in 2008.
 
T

Triple-DES

Dear Den,

Just one question. What do you mean by "unintended conversions"? Could
you explain me bit more detail like when it can happen and so on? I
appreciate that. Thank you very much.

Sure. Consider the following:

void f(Complex c)
{
// ...
}

int main()
{
std::string str("hello");
f(str); // creates a temporary Complex object and calls f(Complex)

Complex c;
if(c == str) // creates a temporary Complex object and calls
// operator==(Complex, Complex) or similar
{
// ...
}
}

The point being that it's harder to spot the creation of the
temporaries in the code. If the constructor is declared explicit, you
would have to write

f( Complex(str) );
and
if( c == Complex(str) )

to compile the code. static_cast<Complex>(str) would also work.

DP
 
J

James Kanze

Alexander Dong Back Kim wrote:
You are aware that Visual C++ 6.0 is 10 years old now and has
many known bugs. Visual C++.NET 2003, which is Visual C++
7.1, and newer versions, have much improved compatibility with
the C++ standard and can compile to native code, too (that is,
not .NET binarys).

They're also available free, so there's really no excuse.
 
J

James Kanze

On Sep 5, 1:15 am, James Kanze <[email protected]> wrote:
The main reason I want to make the "complex" class cast-able
with std::string is I want to convert into a XML file format.
For example,

I'm not sure I understand the abstraction of your class.
Because of the name, I supposed that it was a complex number, in
which case, just about any support for external formats would be
out of place. If it is in fact an XMLComplex, which is used to
map between XML and std::complex, it's a different issue.
Still, conversion is *not* the way C++ handles this problem; you
should define such a class said:
If I have three instance of the class in a vector or some container
class...
vector<Complex> vComplex;
Complex a, b, c;
a = 10;
b = "100";
c = 0;

SaveToXML(vComplex); // Saving function that generates an XML file

I expect the XML look something like...
<Container>
<Complex> "10" </Complex>
<Complex> "100" </Complex>
<Compelx> "0" </Complex>
</Container>

And when you need to support BER, you'll add conversion to a BER
string, and when you need to support XDR, you'll add conversion
to an XDR string, and...

External formats should be separate behavior. You don't want to
mimic the behavior of an existing class (e.g. std::complex) just
to support some particular external format. Conceptually, they
really require some form of double dispatch: to format a value,
you dispatch on the type of the value and a type implementing
the format. In C++, this is usually done by using function or
operator overloading (since the types are normally known
statically anyway, and C++ doesn't support dynamic double
dispatch). Thus, the idiomatic way of supporting this would be
to define an XMLstream, and overload >> and << to input from and
output to this stream. (For input, this might not be the ideal
solution, since XML contains type information that you might
want to exploit dynamically.)

In the case of XML, because the actual stream is text, I'd
probably have the oXMLstream contain a pointer to an
std::eek:stream, which handled the lower level textual formatting.
So you might end up with functions like:

template< typename T >
oXMLstream&
operator<<( oXMLstream& dest, std::vector< T > const& vect )
{
dest.raw() << "<Container>\n" ;
dest.incrementIndentation() ;
for ( std::vector< T >::const_iterator iter = vect.begin() ;
iter != vect.end() ;
++ iter ) {
dest << *iter ;
}
dest.decrementIndentation() ;
dest.raw() << "</Container>\n" ;
return dest ;
}

oXMLstream&
operator<<( oXMLstream& dest, Complex const& obj )
{
dest.raw() << "<Complex> " << obj.value << " </Complex>\n" ;
return dest ;
}

The constructor of oXMLstream would insert a filtering streambuf
between the ostream and its original streambuf, which takes care
of the indentation, with oXMLstream::incrementIndentation and
oXMLstream::decrementIndentation forwarding to this streambuf.
The destructor, of course, would remove the filtering streambuf.
(For more on filtering streambuf's, see
http://kanze.james.neuf.fr/articles/fltrsbf1.html and
http://kanze.james.neuf.fr/articles/fltrsbf2.html; the first
should be largely sufficient for what you are doing. And
there's significant code available for them at my site, or in
boost::iostream; enough so that you shouldn't have to write more
than about 10 lines of code to implement the filtering
streambuf.)

Note that this technique allows you to output pre-existing
types (although I suspect that most of the time, you'll want to
wrap them anyway, to provide semantic specific entity labels).
In order to do this, in my opinion, std::string compatibility
would be the thing really nice to have for further
string-related operations. I'm sorry if my explanation is not
clear enough. If you think my approach is wrong or you think
there are other approaches for doing this kind of thing,
please feel absolutely free to tell and let me know about
them. =)

Well, first, implicit conversions will cause problems in the
long run. And the C++ idiom for formatting doesn't use
std::string, but std::eek:stream (which, of course, can be an
std::eek:stringstream). IMHO, this provides all the chaining you
need, and is a lot more flexible than implicit conversions.
 
A

Alexander Dong Back Kim

I'm not sure I understand the abstraction of your class.
Because of the name, I supposed that it was a complex number, in
which case, just about any support for external formats would be
out of place.  If it is in fact an XMLComplex, which is used to
map between XML and std::complex, it's a different issue.
Still, conversion is *not* the way C++ handles this problem; you
should define such a class, and then << and >> operators on it.




And when you need to support BER, you'll add conversion to a BER
string, and when you need to support XDR, you'll add conversion
to an XDR string, and...

External formats should be separate behavior.  You don't want to
mimic the behavior of an existing class (e.g. std::complex) just
to support some particular external format.  Conceptually, they
really require some form of double dispatch: to format a value,
you dispatch on the type of the value and a type implementing
the format.  In C++, this is usually done by using function or
operator overloading (since the types are normally known
statically anyway, and C++ doesn't support dynamic double
dispatch).  Thus, the idiomatic way of supporting this would be
to define an XMLstream, and overload >> and << to input from and
output to this stream.  (For input, this might not be the ideal
solution, since XML contains type information that you might
want to exploit dynamically.)

In the case of XML, because the actual stream is text, I'd
probably have the oXMLstream contain a pointer to an
std::eek:stream, which handled the lower level textual formatting.
So you might end up with functions like:

    template< typename T >
    oXMLstream&
    operator<<( oXMLstream& dest, std::vector< T > const& vect )
    {
        dest.raw() << "<Container>\n" ;
        dest.incrementIndentation() ;
        for ( std::vector< T >::const_iterator iter = vect.begin() ;
                iter != vect.end() ;
                ++ iter ) {
            dest << *iter ;
        }
        dest.decrementIndentation() ;
        dest.raw() << "</Container>\n" ;
        return dest ;
    }

    oXMLstream&
    operator<<( oXMLstream& dest, Complex const& obj )
    {
        dest.raw() << "<Complex> " << obj.value << " </Complex>\n" ;
        return dest ;
    }

The constructor of oXMLstream would insert a filtering streambuf
between the ostream and its original streambuf, which takes care
of the indentation, with oXMLstream::incrementIndentation and
oXMLstream::decrementIndentation forwarding to this streambuf.
The destructor, of course, would remove the filtering streambuf.
(For more on filtering streambuf's, seehttp://kanze.james.neuf.fr/articles/fltrsbf1.htmlandhttp://kanze.james.neuf.fr/articles/fltrsbf2.html;the first
should be largely sufficient for what you are doing.  And
there's significant code available for them at my site, or in
boost::iostream; enough so that you shouldn't have to write more
than about 10 lines of code to implement the filtering
streambuf.)

Note that this technique allows you to output pre-existing
types (although I suspect that most of the time, you'll want to
wrap them anyway, to provide semantic specific entity labels).


Well, first, implicit conversions will cause problems in the
long run.  And the C++ idiom for formatting doesn't use
std::string, but std::eek:stream (which, of course, can be an
std::eek:stringstream).  IMHO, this provides all the chaining you
need, and is a lot more flexible than implicit conversions.

--
James Kanze (GABI Software)             email:[email protected]
Conseils en informatique orientée objet/
                   Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Thanks for your advice!!!

cheers,
Alex Kim
 

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,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top