Re: Conversion operator not being picked up by compiler
Re: Conversion operator not being picked up by compiler
- Subject: Re: Conversion operator not being picked up by compiler
- From: David Fang <email@hidden>
- Date: Fri, 13 Jan 2006 14:39:58 -0500 (EST)
> --- BEGIN ---
> #include <iostream>
>
> class Foo
> {
> public :
> explicit Foo( const char* message ) : m_str( message ) {}
>
> operator const char*() { return m_str.c_str(); }
> private :
> std::string m_str;
> };
>
> void Write( const char* msg, ... )
> {
> std::cout << msg << std::endl;
> }
>
> int main( int argc, char* const argv[] )
> {
> Foo foo( "Hello, World!" );
> Write( "%s", foo );
> return 0;
> }
> --- END ---
Hi,
(rushed answer:)
I don't *think* code is not well-formed because foo (type Foo) is
passed to a variadic (...) function parameter. The compiler can't deduce
from your format string "%s" that a 'const char*' is sought, and thus
doesn't know to look for an implicit-conversion.
Quick and dirty workarounds: (aside from static_cast<...>)
* write an accessor to Foo that returns const string& ::m_str,
* const char* Foo::c_str(void) const { return m_str.c_str(); }
(a forwarding function)
* overload by adding: (akin to specialization)
void Write(const char* fmt, const Foo& f) {
Write(fmt, /* get string from f */ );
}
The compiler will find this as the best match over
the variadic version.
More robust solutions will require more work, possibly template
magic, but that's getting off-topic.
I did a google search for the following words:
cannot pass objects non-POD type through '...' call will abort runtime
and found some threads that provide similar workarounds.
David Fang
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden