linux-c-programming.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* operator for automatic type conversion not allowed as non-member
@ 2007-07-16  6:05 Shriramana Sharma
  2007-07-16 15:54 ` Glynn Clements
  0 siblings, 1 reply; 2+ messages in thread
From: Shriramana Sharma @ 2007-07-16  6:05 UTC (permalink / raw)
  To: Linux C Programming List

In my program, I would like QString-s (from Qt) to be automatically 
converted to std::string-s. The Qt people could have done this by 
providing an operator std::string () inside class QString but they 
didn't so I tried to do this using a global operator.

operator std::string (const QString & qs) { return qs.toStdString() ; }

but I got:

error: ‘operator std::string(const QString&)’ must be a nonstatic member 
function

Whereas if I try:

const QString operator+ (const std::string & ss, const QString & qs) {
	return QString::fromStdString(ss) + qs ;
}

it works. So what is special about operator othertype that it is not 
allowed to be a non-member?

Similarly operator= is not allowed to be a non-member. So I cannot do:

const std::string & operator= ( std::string & ss, const QString & qs ) {
	ss = qs.toStdString() ;
	return ss ;
}

which is actually meaningful. Of course, since QString has toStdString, 
I can always use that wherever I need to get a std::string from QString, 
but operator overloading is a matter of convenience and I would like to 
know if there is a strong reason that I cannot use operator othertype 
and operator= as a non-member. It would enable me to define convenience 
operators between objects of third-party (which includes the standard 
library for me) types.

Shriramana Sharma.

-
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html

^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2007-07-16 15:54 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2007-07-16  6:05 operator for automatic type conversion not allowed as non-member Shriramana Sharma
2007-07-16 15:54 ` Glynn Clements

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).